獲取 URL 種的參數是經常要處理的功能。在 URL 中,查詢參數字符串值通常提供有關請求的信息,例如搜索參數或正在使用的對象的 ID。如果在前端處理任何業務或請求邏輯,了解如何從 URL 中檢索查詢字符串值非常重要。
// url https://www.zhihu.com/index.shtml?name=devpoint&id=100
// 格式化 search parameters
{
name: "devpoint",
id: "100",
}
常規方式
這是大多數人使用它的方式。
const parseQuery = (search = window.location.search) => {
const query = {};
search
.slice(1)
.split("&")
.forEach((it) => {
const [key, value] = it.split("=");
query[key] = decodeURIComponent(value);
});
return query;
};
console.log(parseQuery("?name=devpoint&id=100")); // { name: 'devpoint', id: '100' }
使用 reduce
const parseQuery = (search = window.location.search) =>
search
.replace(/(^\?)|(&$)/g, "")
.split("&")
.reduce((query, it) => {
const [key, value] = it.split("=");
query[key] = decodeURIComponent(value);
return query;
}, {});
console.log(parseQuery("?name=devpoint&id=100")); // { name: 'devpoint', id: '100' }