const queryString = (url) => {
// 从 URL 中提取查询字符串
const queryString = new URL(url).search.slice(1);
// 将查询字符串解析为键值对
const keyValuePairs = queryString.split('&');
// 创建一个空对象来存储结果
let result = {};
keyValuePairs.forEach(pair => {
let [key, value] = pair.split('=');
let keys = key.split('.');
let temp = result;
keys.forEach((key, index) => {
value = decodeURIComponent(value);
// 如果是最后一个键,直接赋值
if (index === keys.length - 1) {
temp[key] = value;
} else {
// 如果不是最后一个键,且该键对应的值不是对象,则将其设为空对象
if (typeof temp[key] !== 'object' || temp[key] === null) {
temp[key] = {};
}
}
// 更新临时对象
temp = temp[key];
});
});
return result;
}
// 示例用法
let url = 'https://xxxxxxxxx.com?name=feizhu&from=a&j=frontend&extraInfo.a=b&extraInfo.c=d';
console.log(queryString(url)); // 输出:{name:"feizhu",from:'a',j:'frontend',extraInfo: {a: 'b', c: 'd'}}
01-20
308
11-27
1198