尝试重定向到同一页面但具有查询字符串值

Trying to redirect to the same page but with querystring value

我想重定向到同一页面,但添加了一些查询字符串值。

如果已经有一个查询字符串值,我想将其删除并添加一个新值。

我的代码目前无法运行,不知道为什么:

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

问题是您在剥离旧的查询字符串时没有添加新的查询字符串,只有在没有旧查询字符串的情况下才在 else 子句中添加。从 else 中删除该添加项,这样您就可以一直这样做。

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

最好使用已经可用的 URL API.

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

您可以查看以下链接以了解更多信息: