解析查询字符串
程序员文章站
2022-07-14 08:24:02
...
var queryStr = "https://www.baidu.com/s?wd=%E5%90%89%E5%B0%94%E6%8B%9C%E7%99%BB&rsv_spt=1&rsv_iqid=0x8918dabe0005151c&issp=1&f=3&rsv_bp=1&rsv_idx=2&ie=utf-8&tn=baiduhome_pg&rsv_enter=1&rsv_dl=ih_0&rsv_sug3=1&rsv_sug1=1&rsv_sug7=001&rsv_sug2=1&rsv_btype=i&rsp=0&rsv_sug9=es_2_1&rsv_sug4=3943&rsv_sug=9#miaodian";
var queryObj = parseQuery(queryStr);
for(var key in queryObj){
console.log(key+":"+queryObj[key]);
}
function parseQuery(queryStr){
var query = {};
var start = queryStr.indexOf("?");
var end = queryStr.indexOf("#");
if(start == -1){
return query;
}
var temp = queryStr.slice(start+1,end);
var queryArr = temp.split("&");
// for(var i=0;i<queryArr.length;i++){
// var arr = queryArr[i].split("=");
// //query.arr[0] = arr[1];
// query[arr[0]] = arr[1];
// }
queryArr.forEach(function(item,index,arr){
var arr = item.split("=");
//query.arr[0] = arr[1];
query[arr[0]] = arr[1];
});
return query;
}
效果图: