获取路径中参数的值, 并转换为json对象
使用正则表达式
function getParamsFromURL(url) {
const regex = /[?&]([^=#]+)=([^&#]*)/g;
const params = {};
let match;
while (match = regex.exec(url)) {
params[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);
}
return params;
}
const url = 'http://example.com?param1=value1¶m2=value2';
const params = getParamsFromURL(url);
console.log(params); // 输出:{ param1: 'value1', param2: 'value2' }
使用URLSearchParams对象
function getParamsFromURL(url) {
const searchParams = new URLSearchParams(url.split('?')[1]);
const params = {};
for (let param of searchParams) {
params[param[0]] = param[1];
}
return params;
}
const url = 'http://example.com?param1=value1¶m2=value2';
const params = getParamsFromURL(url);
console.log(params); // 输出:{ param1: 'value1', param2: 'value2' }