Javascript 在JS中处理查询字符串,如http\U build\U查询等
这是我的Javascript 在JS中处理查询字符串,如http\U build\U查询等,javascript,query-string,location-href,Javascript,Query String,Location Href,这是我的 if(condition1) { location.href = location.href+'/?site_type=normal'; } else if(condition2) { location.href = location.href+'/?site_type=other'; } 当然,如果location.href上已经有了查询变量,那就是一个问题,等等 我需要 从查询字符串中查找变量 如果站点类型已存在,请将该值替换为“正常”或“其他” 使用新站点类型
if(condition1) {
location.href = location.href+'/?site_type=normal';
}
else if(condition2) {
location.href = location.href+'/?site_type=other';
}
当然,如果location.href上已经有了查询变量,那就是一个问题,等等
我需要
- domain.com
- domain.com/path/to/sth/
- domain.com/?站点类型=正常
- 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);
以下是一种方法:
//remove existing param and append new one..
var newHref = window.location.href.replace(window.location.search,"") + '?site_type=other';
//change href
window.location.href = newHref;
仅当您有一个要替换的参数时才起作用,否则它将删除所有参数。您可以使用
window.location.search直接访问查询字符串。您可以使用这个正则表达式技巧将其转换为对象
然后在queryString
上适当设置site\u type
queryString["site_type"] = "normal";
最后,将其转换回字符串,并将其设置为window.location.search
var searchString = "";
for ( q in queryString ) {
searchString+="&" + q + "=" + queryString[q];
}
window.location.search = searchString;
例如,如果你有
yourpage.com/?site\u type=normal
你只需要网站而不是查询变量,你就可以清除它们
var novars= location.href.replace(window.location.search,"")
本案例novars=youroage.com
对于仅获取变量,您可以执行以下操作:
var site_type = window.location.search.replace("?site_type=","");
在这里,我将得到site_type值,无论是正常值还是其他值
这种情况下,您的变量site\u type=“normal”
要重建url,您只需添加新的站点类型即可
location.href = novars+"?site_type=normal"
或
当然你可以检查(window.location.search==”)
,如果你关心额外的&
。我用一个解决方案编辑了我的答案,希望现在能解决所有问题。太好了!看起来js会在将搜索字符串附加到window.location之前自动从搜索字符串中去掉前面的“&”?有没有办法将“window.location.search=searchString”放入变量中,这样我就可以对其进行console.log操作?这只是为了让我理解它,它似乎与我抛出的任何类型的url一起工作。相关(考虑重复键):
location.href = novars+"?site_type=normal"
location.href = novars+"?site_type=other"