js提取url后面的参数
例: http://127.0.0.1:5500/url.html?id=1&user=2
方法一 :公共版
tool 可以定义成公共方法
var tool = {}
Object.assign(tool,{
GetRequest() {
var url = decodeURIComponent(location.search); //获取url中"?"符后的字串
var theRequest = new Object();
if (url.indexOf('?') != -1) {
var str = url.substr(1);
var strs = str.split('&');
for (var i = 0; i < strs.length; i++) {
var str = strs[i].slice(strs[i].indexOf('=') + 1, strs[i].length);
theRequest[strs[i].split('=')[0]] = str;
}
}
return theRequest;
}
})
适用于大型项目公告方法
方法二 :简易版
var url = decodeURIComponent(location.search).substr(1).split('&')
var theRequest = new Object();
url.forEach(function(item){
theRequest[item.split('=')[0]] = item.split('=')[1];
})
console.log(theRequest)
方法三:多功能
function parseURL(url) {
const result = { url: '', params: {} };
if (url) {
const [pureURL, searchParams] = url.split('?');
result.url = pureURL;
if (searchParams) {
result.params = searchParams.split('&').reduce((params, kv) => {
const [k, v] = kv.split('=');
params[k] = v;
return params;
}, {});
}
}
console.log(result)
};
PS:勿喷