Blankman
Blankman

Reputation: 267320

Trying to redirect to the same page but with querystring value

I want to redirect to the same page, but add some querystring values.

If there is already a querystring value, I want to strip it out and add a new one.

My code isn't working currently, not sure why:

var url = window.location.href;
if(url.indexOf("?") > 0) {
  url = url.substring(0, url.indexOf("?"));
} else {
    url += "?joined=true";
}
window.location.replace(url);

Upvotes: 3

Views: 6733

Answers (2)

Arnelle Balane
Arnelle Balane

Reputation: 5497

It would be better to use the already-available URL API.

var url = new URL(window.location.href);
url.searchParams.set('joined', true);
window.location.replace(url.toString());

You can check the following links to learn more about it:

Upvotes: 6

Barmar
Barmar

Reputation: 782683

The problem is that you're not adding the new query string when you strip off the old one, only in the else clause when there's no old query string. Take that addition out of the else, so you do it all the time.

var url = window.location.href;
if(url.indexOf("?") > 0) {
  url = url.substring(0, url.indexOf("?"));
} 
url += "?joined=true";
window.location.replace(url);

Upvotes: 10

Related Questions