这就是我所拥有的
if(condition1) {
location.href = location.href+'/?site_type=normal';
}
else if(condition2) {
location.href = location.href+'/?site_type=other';
}
当然,如果 location.href 上已经有查询变量,那就有问题了,等等。
我需要
- 从查询字符串中查找变量
- 如果 site_type 已经存在,则将该值替换为“正常”或“其他”
- 使用新的 site_type 重建 url
编辑:我发现我需要考虑各种 URL:
- 域名.com
- domain.com/path/to/sth/
- domain.com/?site_type=正常
- domain.com?var=123&foo=987
- domain.com/path/?site_type=normal&var=123&foo=987
所以,这是我想出的,欢迎提出建议:
var searchstring = window.location.search;
var url = window.location.href;
console.log('search: ' + searchstring);
console.log( 'url: ' + url);
// strip search from url
url = url.replace(searchstring,"");
console.log( 'url: ' + url);
//strip site_type from search
searchstring = searchstring.replace("&site_type=normal","")
.replace("&site_type=other","")
.replace("?site_type=normal","")
.replace("?site_type=other","")
.replace("?","")
;
console.log('search: ' + searchstring);
if(searchstring != ''){searchstring = '&' + searchstring;}
var final = url + '?site_type=normal' + searchstring;
final = final.replace("&&","&");
console.log('final: ' + final);