1

In my shopping cart I create affiliate urls like so:

http://mysite.local/phones-and-pdas/iphone?z=5509d173cffeb

I'd like to use history.pushState to remove the query string starting at the ?.

I've tried using slice() and split() but this seems to effect other urls as well, even when they don't contain ?z=

function trackingLink() {
    var href = window.location.href;
    var url  = href.slice(0, href.indexOf('?z='));

    history.pushState(null, null, url);
}

For example when I go to:

http://mysite.local/account/dashboard

The address url is changed to:

http://mysite.local/account/dashboar

As a note, the above code does work perfectly on the affiliate link.

I'm sure this is a simple tweak but I couldn't find a specific answer when searching.

4 Answers 4

2
function trackingLink() {
var href = window.location.href;
var url  = href.split('?z=');
history.pushState(null, null, url[0]);
}
1
  • Perfect, thanks. I tried split but I did it wrong. Appreciate the help.
    – secondman
    Mar 19, 2015 at 19:59
2

Look at split instead of slice.

href.split('?')[0] should work.

0
1

Add a check to see if ?z= there in the first place:

var href = window.location.href;
if(href.indexOf('?z=')) {
    var url  = href.slice(0, href.indexOf('?z='));
    history.pushState(null, null, url);
}
0

Just to elaborte on +DaveS's answer:

var href = window.location.href;
var url = href.split("?")[0];
history.pushState(null, document.title, url);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.