let getQueryStringArgs=function(){ //取得没有开头问号的查询字符串 let qs=(location.search.length>0)?location.search.substring(1):""; let args={}; for(let item of(qs.split('&').map(kv=>kv.split('=')))){ let name=item[0]; value=item[1]; if(name.length){ args[name]=value; } } return args; } //qs="?q=javaScript&num=10"; let args=getQueryStringArgs(); alert(args["q"]); alert(args['num']);
使用USLSearchParams检查和修改查询字符串
1 2 3 4 5 6 7 8 9 10 11 12
let qs="?q=javaScript&num=10"; let searchParams=new URLSearchParams(qs); alert(searchParams.toString()); searchParams.has("num"); searchParams.get("num"); searchParams.set("page","3"); alert(searchParams.toString()); searchParams.delete("q"); alert(searchParams.toString()); for(let param of searchParams){ console.log(param); }