Js获取Url地址参数的几种方法
方法一 URLSearchParams()函数
geturlparam(){
let that=this
// window.location.href 获取地址
let url = https://xxxx.com/xxx/demo?type=1&id=2
let p=url.split(?)[1]
let params=new URLSearchParams(p)
console.log(params.get(type)) //1
console.log(params.get(id)) //2
}
方法二 split()截取
geturlparam() {
let that = this
// window.location.href 获取地址
let url = https://xxxx.com/xxx/demo?type=1&id=2
let p = url.split(?)[1]
let keyValue = p.split(&);
let obj = {};
for (let i = 0; i < keyValue.length; i++) {
let item = keyValue[i].split(=);
let key = item[0];
let value = item[1];
obj[key] = value;
}
console.log(keyValue); // [type=1,id=2]
console.log(obj); // {type:1,id:2}
},
上述两种方法的地址是比较规范的,像只以 / 连接的地址我一般是这种方法,也是split截取
geturlparam() {
let that = this
// window.location.href 获取地址
let url = https://xxxx.com/xxx/demo/type/1/id/2
if (url.indexOf(/type/) != -1) {
that.type = url.split("/type/")[1].split("/")[0]; //1
that.id = url.split("/id/")[1].split("/")[0]; //2
}
},
split比较随心所欲,看自己业务需求,想怎么截就怎么截
