在工作中,时常会有从地址栏中拿取对应的参数,当参数过多时,我们会考虑封装成一个方法,将参数放在对象中返回,这样获取会更加方便,下面列出了两中方法。
- 第一种
//路径 https://editor.csdn.net/md?articleId=1&&articleNum=1&opt=edit
getUrlParams = () => {
let url = window.location.search;//?articleId=1&&articleNum=1&opt=edit
let index = url.indexOf('?')
let obj = {}
if (index !== -1) {
let str = url.substr(1)
let arr = str.split('&')
for (let i = 0; i < arr.length; i++) {
obj[arr[i].split('=')[0]] = arr[i].split('=')[1]
}
}
return obj//{articleId: "1", articleNum: "1", opt: "edit"}
}
- 第二种
getUrlParams = locationSearch=> {
var obj = {};
var search = locationSearch;
search = /\?/.test(search) && search.split("?")[1];// \? 表示一个 ? 字符
var searchs = /\&/.test(search) ? search.split("&") : [search];
for (var i = 0; i < searchs.length; i++) {
if (/\=/.test(searchs[i])) {
var item = searchs[i].split("=");
params[item[0]] = item[1];
};
};
return obj;
};