// 當前頁面 URL
const params = new URLSearchParams(window.location.search);
// 獲取單個參數
const keyword = params.get('keyword'); // "search-term"
const pid = params.get('pid'); // "37"
// 獲取所有同名參數(陣列)
const tags = params.getAll('tag'); // ["js", "css"]
// 判斷是否存在
if (params.has('debug')) { /* ... */ }
// 遍歷所有參數
for (const [key, value] of params) {
console.log(key, value);
}
優點:原生、無依賴、自動處理編碼/解碼、支援迭代器。
/**
* 解析 URL 查詢字符串為物件
* @param {string} [url=window.location.href] 目標 URL
* @returns {Object} 參數鍵值對,同名參數取最後一個
*/
function parseQueryString(url = window.location.href) {
const queryIndex = url.indexOf('?');
if (queryIndex === -1) return {};
const queryString = url.slice(queryIndex + 1).split('#')[0]; // 去除 hash
const params = {};
queryString.split('&').forEach(pair => {
const [key, value] = pair.split('=').map(decodeURIComponent);
if (key) params[key] = value; // 同名覆蓋,若需陣列可改為 params[key] = params[key] ? [].concat(params[key], value) : value
});
return params;
}
// 使用
const { keyword, pid } = parseQueryString();
console.log(keyword, pid);
function getParam(name, url = window.location.href) {
const regex = new RegExp('[?&]' + name + '=([^]*)');
const match = url.match(regex);
return match ? decodeURIComponent(match[1]) : null;
}
const pid = getParam('pid'); // "37"
注意:正則需轉義特殊字符,且不支援同名多值。
%、+、空格等,務必使用 decodeURIComponent 解碼。location.search 不包含 # 後內容,但手動傳入完整 URL 時需手動切分。?id=1&id=2,URLSearchParams.get() 取第一個,getAll() 取全部;自定義解析需決定策略。?flag 或 ?flag=,get() 返回空字符串,自定義解析需處理無 = 情況。URLSearchParams。parseQueryString。getParam() 正則法最輕量。