应用场景:
针对web前端开发嵌套在APP项目的H5页面,在进行页面开发时需要拿到APP开发同事放入地址栏中的用户信息。
1. 问题描述:
开发状态中的http://localhost:8080/#/xxx
绝不是我们想要的地址。
而是项目发版后的地址:http://101.230.192.1xx/ebank/index.html#/bank?userId=5233&userName=王有才
,目的是要拿到?后面的userId=5233&userName=王有才
2. 解决方法:
getLocationDate() {
let obj = {};
let urlDate = window.location.hash;// http://101.230.192.1xx/ebank/index.html#/bank?userId=5233&userName=王有才
let reg = /[?&][^?&]+=[^?&]+/g;
let arr = urlDate.match(reg); // 利用正则得到 ['?userId=5233', '&userName=王有才']
if (arr) {
arr.forEach((item) => {
let tempArr = item.substring(1).split("="); // 截取字符串并以'='拆分字符串。 参考item ——> ['userId', '5233'] ['userName', '王有才']
let key = decodeURIComponent(tempArr[0]); // 解码数组下标为0的值做为key。 参考item ——> userId userName
let value = decodeURIComponent(tempArr[1]); // 解码数组下标为1的值做为value。 参考item ——> 5233 王有才
obj[key] = value;
});
}
console.log("得到地址栏中的参数",obj); // {userId: '5233', userName: '王有才'}
},