获取URL后缀的参数

分享一下URL跳转后面拼接参数获取参数的方法:

之前一直用的是这个方法,不管URL后面有几个参数,一个个的去获取,感觉比较麻烦了,不实用了,所以区分了一下,
如果URL后面只跟一个参数的话,可以用这个方法获取

1
2
3
4
5
6
7
8
9
10
11
function getParamVal(type) {
const { href } = window.location;
let res = '';
let startIndex = href.lastIndexOf(type);
if (startIndex !== -1) {
startIndex = href.indexOf('=', startIndex) + 1;
const endIndex = href.indexOf('&', startIndex);
res = endIndex !== -1 ? href.substring(startIndex, endIndex) : href.substring(startIndex);
}
return res;
}

如果URL后面有多个参数的话,可以用这个方法获取,它是以对象的形式返回的

1
2
3
4
5
6
7
8
9
10
11
12
13
function getParamObj(){
const url = document.location.toString();
let suffixObj = url.split("?");
const params = Object.create(null)
if (suffixObj.length > 1){
suffixObj = suffixObj[1].split("&");
suffixObj.forEach(item=>{
item = item.split("=");
params[item[0]] = item[1]
});
}
return params;
}