获取URL查询参数转换成对象
正则表达式
多个非“[^?&=]+”字符后面接等于号“=”,后面分组为任意个非“?&=”字符,即”=”号后的参数可以为空和任意非上述的特殊字符
//多个非“[^?&=]+”字符
/([^?&=]+)=([^?&=]*)/g
实例
const quryToObj = (url) => {
let params = url.split("?")[1].split("&");
let obj = {};
params.map(v => obj[v.split("=")[0]] = v.split("=")[1]);
return obj;
};
const getQueryObject = (url) => {
url = url == null ? window.location.href : url;
let search = url.substring(url.lastIndexOf("?") + 1);
let obj = {};
let reg = /([^?&=]+)=([^?&=]*)/g;
// var reg = /(.*)=(.*)/g;
let str = search.replace(reg, function (rs, $1, $2) {
let name = decodeURIComponent($1);
let val = decodeURIComponent($2);
val = String(val);
obj[name] = val;
return rs;
});
return obj;
}
console.log(quryToObj("http://www.test.net?id=123&a=1&bb=b"));
console.log(getQueryObject("http://www.test.xxx.net?id=345&a=2&a=d"));