function serilizeUrl(url) {
var urlObj = {};
if (/\?/.test(url)) {
var urlString = url.subString(url.indexOf('?') + 1);
var urlArray = urlString.split('&');
for (var i = 0, len = urlArray.length; i < len; i++) {
var urlItem = urlArray[i];
var item = urlItem.split('=');
urlObj[item[0]] = item[1];
}
return urlObj;
}
return null;
}
方法二:使用正则表达式和 URLSearchParams 对象
function extractUrlParams(url) {
const params = {};
const queryString = url.split('?')[1];
if (queryString) {
const searchParams = new URLSearchParams(queryString);
for (let [key, value] of searchParams) {
params[key] = value;
}
}
return JSON.stringify(params);
}
const url = 'https://www.example.com/?name=Alice&age=30';
const extractedParams = extractUrlParams(url);
console.log(extractedParams);
方法三:使用 URLSearchParams 对象的 entries() 方法
function extractUrlParams(url) {
const params = {};
const queryString = url.split('?')[1];
if (queryString) {
const searchParams = new URLSearchParams(queryString);
for (let [key, value] of searchParams.entries()) {
params[key] = value;
}
}
return JSON.stringify(params);
}
const url = 'https://www.example.com/?name=Alice&age=30';
const extractedParams = extractUrlParams(url);
console.log(extractedParams);