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);
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);
Share
Improve this question
asked Apr 7, 2017 at 3:12
BlankmanBlankman
267k330 gold badges795 silver badges1.2k bronze badges
1
-
As an aside, note that
.indexOf()
returns -1 if the substring isn't found, so normally you'd use a condition> -1
or!= -1
. (It doesn't matter for this example, because your URL isn't going to have a?
as its first character, but still...) – nnnnnn Commented Apr 7, 2017 at 3:17
2 Answers
Reset to default 10The 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);
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:
- https://developer.mozilla/en/docs/Web/API/URL
- https://developer.mozilla/en-US/docs/Web/API/URLSearchParams