history.pushState how can I get rid of get parameters?

2.6k views Asked by At

I am using

  history.pushState('id','myTitle','myURL');

to manipulate the displayed URL and the history stack. At some point I am pushing get parameters like so:

history.pushState('id','myTitle','?mySubLinkedStuff=hotSubLinkedStuff');

Now when I do

history.pushState('id','myTitle','#justSomeHashtag');

it produces http://example.com?mySubLinkedStuff=hotSubLinkedStuff#justSomeHashtag I can also overwrite the value of mySubLinkedStuff but not seem to be able to get rif of it alltogether.

Desired result:

http://example.com#justSomeHashtag or http://example.com/#justSomeHashtag

and obviously I don't want to make the whole roundtrip over the server and I also want to avoid using absolute path or URL to keep the project portable.

2

There are 2 answers

0
Max On

As NimrodArgov rightly remarked: overwriting existing get-parameter strings works if you push the full URL. So for ensuring portability of the app (keep it usable on various domains) I did this:

history.statePush(document.location.origin + window.location.pathname + '#myHashValue');

Works perfectly well and fast.

0
jesus2099 On

To push current address without GET parameters :

history.pushState("id", "myTitle", 
  location.protocol + "//" + location.host +
  location.pathname + location.hash
);

Other than that ;

To push a hash change I could do :

history.pushState("id", "myTitle", 
  location.protocol + "//" + location.host +
  location.pathname + location.search + "#myHashHere"
);

To push a query change I could do :

history.pushState("id", "myTitle", 
  location.protocol + "//" + location.host +
  location.pathname + "?my=query&over=here" + location.hash
);

※ Sorry I don’t have enough karma to just comment on Max’s answer… :/