Appearance
获取url中的查询键值对
本节目标:理解“获取url中的查询键值对”的核心思路,并能把它用于实际开发或面试表达。
getUrlParam(key, search = window.location.search) {
if (!key) {
let params = {};
search.replace(/([^=?&]*)=([^&]*)/g, (_, key, value) => {
params[decodeURIComponent(key)] = decodeURIComponent(value);
return params;
});
return params;
}
let pattern = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
let match = search.substr(1).match(pattern);
return match !== null ? decodeURIComponent(match[2]) : null;
},