url参数
本文仅作为本人工作常用工具总结
支持多种参数拼接方式 1.哈希前后均有参数:http://www.xxx.com/test?a=1&b=2#hello?c=3&a=4 2.哈希前带参数:http://www.xxx.com/test?a=1&b=2#hello 3.哈希后带参数:http://www.xxx.com/test#hello?c=3&a=4
function parseParam(url = window.location.href) {
const temporaryUrl = decodeURIComponent(encodeURIComponent(url));
const paramsStrList = temporaryUrl.match(/\??(\w+)=(\w+)&?/g);
const paramsObj = {};
if (!paramsStrList) return {}
paramsStrList.forEach(item => {
const param = item.replace(/\?|&|#/g, '');
if (/=/.test(param)) {
let [key, val] = param.split('=');
val = decodeURIComponent(val);
val = /^\d+$/.test(val) ? parseFloat(val) : val;
if (Object.prototype.hasOwnProperty.call(paramsObj, 'key')) {
paramsObj[key] = [].concat(paramsObj[key], val);
} else {
paramsObj[key] = val;
}
} else {
paramsObj[param] = true;
}
})
return paramsObj;
}
|