獲取 URL 查詢參數是前端路由、數據傳遞、埋點分析的基礎技能。從早期的正則匹配到現代 URLSearchParams API,本文系統梳理各種方案的優缺點、兼容性、性能與最佳實踐,助你選對工具、寫對代碼。
https://example.com/path/page?name=value&id=123#hash
│ │ │ │
│ │ │ └─ hash (錨點,不發送給服務器)
│ │ └─ search (查詢字符串,含 ?)
│ └─ pathname
└─ origin (protocol + host)
| 方案 | API/方法 | 瀏覽器支持 | 優點 | 缺點 | 推薦指數 |
|---|---|---|---|---|---|
| 正則匹配 | 手寫 RegExp | 全支持 (IE6+) | 無依賴、可控性強 | 易出錯、需手動 decode、不支持多值同名 | ⭐⭐ (舊項目維護) |
| split/循環解析 | 字符串分割 | 全支持 | 邏輯直觀 | 性能差、繁瑣、同樣需手動 decode | ⭐ (教學用) |
| URLSearchParams | new URLSearchParams(search) | IE 無支持,現代全支持 | 標準 API、自動編解碼、支持多值、鏈式操作 | IE 需 polyfill | ⭐⭐⭐⭐⭐ (現代首選) |
| URL 對象 | new URL(href) | IE 無支持,現代全支持 | 解析完整 URL、屬性訪問便捷 | IE 需 polyfill、較重 | ⭐⭐⭐⭐ (需解析完整 URL 時) |
| 第三方庫 | query-string, qs | 全支持 | 功能豐富(嵌套對象、數組)、Node 同構 | 增加體積 | ⭐⭐⭐ (複雜場景) |
// 1. 從當前頁面獲取
const params = new URLSearchParams(window.location.search);
// 2. 從任意 URL 字符串獲取
const url = 'https://example.com?name=张三&id=123&tag=js&tag=ts';
const params2 = new URLSearchParams(new URL(url).search);
// 核心操作
params.get('name'); // '张三' (首個值,自動 decode)
params.getAll('tag'); // ['js', 'ts'] (所有值)
params.has('id'); // true
params.keys(); // 迭代器: 'name', 'id', 'tag'
params.values(); // 迭代器: '张三', '123', 'js', 'ts'
params.entries(); // 迭代器: ['name','张三'], ['id','123']...
params.toString(); // 'name=张三&id=123&tag=js&tag=ts' (自動 encode)
[...params]; // [['name','张三'], ['id','123'], ['tag','js'], ['tag','ts']]
// 修改操作 (會改變實例)
params.set('id', '456'); // 設置/替換
params.append('tag', 'vue'); // 追加同名值
params.delete('name'); // 刪除
params.sort(); // 按鍵名排序
const obj = Object.fromEntries(params);
// { name: '张三', id: '456', tag: 'vue' }
const obj = {};
for (const [k, v] of params) {
if (obj[k] === undefined) obj[k] = v;
else obj[k] = Array.isArray(obj[k]) ? [...obj[k], v] : [obj[k], v];
}
// { name: '张三', id: '456', tag: ['js', 'ts', 'vue'] }
const url = new URL('https://example.com/path?name=value#hash');
url.searchParams.get('name'); // 'value'
url.origin; // 'https://example.com'
url.hostname; // 'example.com'
url.pathname; // '/path'
url.hash; // '#hash'
url.href; // 完整 URL
// 修改參數並獲取新 URL
url.searchParams.set('page', '2');
url.toString(); // 'https://example.com/path?name=value&page=2#hash'
function getQueryParam(name, url = window.location.href) {
// 1. 提取 search 部分 (去掉 #hash)
const search = url.split('#')[0].split('?')[1] || '';
// 2. 正則匹配: 參數名=值(&或結尾)
// 注意:參數名需轉義特殊字符
const regex = new RegExp('[?&]' + name.replace(/[\[\]]/g, '\\$&') + '=([^&]*)');
const match = search.match(regex);
return match ? decodeURIComponent(match[1].replace(/\+/g, ' ')) : null;
}
// 獲取所有參數對象
function getAllParams(url = window.location.href) {
const search = url.split('#')[0].split('?')[1] || '';
const params = {};
search.split('&').forEach(pair => {
const [key, val = ''] = pair.split('=');
const decodedKey = decodeURIComponent(key.replace(/\+/g, ' '));
const decodedVal = decodeURIComponent(val.replace(/\+/g, ' '));
if (params[decodedKey] === undefined) params[decodedKey] = decodedVal;
else params[decodedKey] = Array.isArray(params[decodedKey]) ? [...params[decodedKey], decodedVal] : [params[decodedKey], decodedVal];
});
return params;
}
// Node.js 18+ 原生支持 URL, URLSearchParams
const { URL, URLSearchParams } = require('url'); // 或全局可用
// 處理複雜嵌套對象/數組 (如 a[b]=1&a[c]=2 → {a:{b:1,c:2}})
// 推薦使用成熟庫: qs (Express 默認), query-string
const qs = require('qs');
qs.parse('a[b]=1&a[c]=2'); // { a: { b: '1', c: '2' } }
qs.stringify({ a: { b: 1, c: 2 } }); // 'a[b]=1&a[c]=2'
// 1. 官方 polyfill (推薦)
<script src="https://cdn.jsdelivr.net/npm/url-search-params-polyfill@latest/url-search-params.js"></script>
// 2. 或 core-js
import 'core-js/stable/url-search-params';
import 'core-js/stable/url';
// 3. 簡易 polyfill (僅基礎 get/getAll/set/append/delete/toString)
if (typeof URLSearchParams === 'undefined') {
window.URLSearchParams = function(search) { /* 簡易實現 */ };
}
// useQueryParams.js (Vue 3 Composition API / React Hook)
export function useQueryParams() {
const params = new URLSearchParams(window.location.search);
const get = (key) => params.get(key);
const getAll = (key) => params.getAll(key);
const getNumber = (key, defaultVal = 0) => Number(params.get(key)) || defaultVal;
const getBoolean = (key) => params.get(key) === 'true';
const set = (key, val) => {
params.set(key, val);
updateUrl();
};
const remove = (key) => {
params.delete(key);
updateUrl();
};
function updateUrl() {
const newUrl = `${location.origin}${location.pathname}?${params.toString()}${location.hash}`;
history.replaceState(null, '', newUrl); // 不添加歷史記錄
// 或 history.pushState(null, '', newUrl); // 添加歷史記錄
}
return { params, get, getAll, getNumber, getBoolean, set, remove };
}
interface QueryParams {
page: number;
size: number;
keyword?: string;
tags?: string[];
}
function getTypedParams>(): Partial {
const params = new URLSearchParams(window.location.search);
const result = {} as Partial;
for (const key of params.keys()) {
const vals = params.getAll(key);
// 簡單類型推斷:數字、布爾、數組
if (vals.length === 1) {
const v = vals[0];
if (/^\d+$/.test(v)) result[key] = Number(v);
else if (v === 'true' || v === 'false') result[key] = v === 'true';
else result[key] = v;
} else {
result[key] = vals;
}
}
return result;
}
URLSearchParams 內部已正確處理。現代項目首選 URLSearchParams:標準化、自動編解碼、支持多值、鏈式 API、輕量。配合 core-js polyfill 完美兼容 IE。
需解析完整 URL 時用 new URL()。
複雜嵌套對象序列化用 qs/query-string。
避免手寫正則/分割解析,極易踩編碼、多值、邊界坑。
封裝通用工具函數/Hook,統一項目參數獲取規範,提升開發效率與代碼質量。