最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Trying to redirect to the same page but with querystring value - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 10

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);

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
发布评论

评论列表(0)

  1. 暂无评论