获取 URL 并解析查询参数
🌙
手机阅读
本文目录结构
需求
获取 url 地址里面查询情况(可能包含 Hash)
https://www.axihe.com/?name=anbang&age=30#%E6%A0%87%E7%AD%BE
{
"name":"anbang",
"age":"30",
"hash":"标签"
}
每一项都可能有,也可能没有
代码
var str1 = 'https://www.axihe.com/?name=anbang&age=30#%E6%A0%87%E7%AD%BE';
var str2 = 'https://www.axihe.com/?name=安邦&age=三十#%E6%A0%87%E7%AD%BE';
function parseUrl(url) {
let obj = {};
// 除了?=&#以外都是有效的值
url.replace(/([^?=&#]+)=([^?=&#]+)/g, (...arg) => {
// console.log('arg', arg);
obj[arg[1]] = decodeURIComponent(arg[2]);
});
url.replace(/#([^?=&#]+)/g, (...arg) => {
// console.log('arg', arg);
obj['HASH'] = decodeURIComponent(arg[1]);
});
return obj;
}
console.log(parseUrl(str1));//{name: "anbang", age: "30", HASH: "标签"}
console.log(parseUrl(str2));//{name: "安邦", age: "三十", HASH: "标签"}