我有一个网址:
domain.com/?page=2&show=10&sortterm=km
如果我第二次排序,网址就会变成
domain.com/?page=2&show=10&sortterm=km&sortterm=km
我想做的是:
1. see if url has "?" in it
2. if yes,
2.1. see if "sortterm" exists in url
2.2. if yes, replace that "&sortterm=x" with new "&sortterm=y"
2.3. if not, add "&sortterm=y"
3. if not
3.1 add "?sortterm=y"
这是我的代码:
var url = String(window.location);
if(url.indexOf("?") !== -1){
if(url.indexOf('sortterm') !== -1){
var newurl = url +'&sortterm='+sortterm;
//^ but i need to replace here, and the value of sortterm can be different.
}
...
...
我有点卡住,求助!
答案 0 :(得分:2)
此
url = url.replace(/([&?]sortterm=)[^&]*/, "$1" + sortterm)