從 URL 取得查詢參數是前端基礎需求。本文從傳統正則解析演進至現代 URLSearchParams API,提供完整相容方案、型別轉換、陣列參數、編碼處理與 TypeScript 類型安全封裝。
// 直接從 location.search 建立
const params = new URLSearchParams(location.search);
// 取得單一值 (第一個)
const id = params.get('id'); // "123" 或 null
// 取得所有同名值 (陣列)
const tags = params.getAll('tag'); // ["js", "css", "html"]
// 判斷是否存在
const hasSort = params.has('sort'); // true/false
// 迭代所有參數
for (const [key, value] of params) {
console.log(key, value);
}
// 轉物件 (注意:同名參數只保留最後一個)
const obj = Object.fromEntries(params);
/**
* 解析 URL 查詢字串
* @param {string} [url=window.location.href] - 目標 URL
* @returns {URLSearchParams} 可鏈式操作的參數物件
*/
function getQueryParams(url = window.location.href) {
try {
const parsed = new URL(url);
return new URLSearchParams(parsed.search);
} catch {
// 降級:手動解析
const search = url.split('?')[1] || '';
return new URLSearchParams(search);
}
}
/**
* 取得參數值 (支援型別轉換)
* @param {string} key - 參數名
* @param {URLSearchParams} [params] - 可選預解析物件
* @returns {string|null}
*/
function getParam(key, params = getQueryParams()) {
return params.get(key);
}
/**
* 取得參數陣列值
*/
function getParamAll(key, params = getQueryParams()) {
return params.getAll(key);
}
/**
* 取得布林值參數
*/
function getParamBool(key, params = getQueryParams()) {
const val = params.get(key);
return val === 'true' || val === '1' || val === 'yes';
}
/**
* 取得數字參數
*/
function getParamNumber(key, params = getQueryParams()) {
const val = params.get(key);
return val !== null ? Number(val) : null;
}
/**
* 取得 JSON 解析參數
*/
function getParamJSON(key, params = getQueryParams()) {
const val = params.get(key);
try {
return val ? JSON.parse(decodeURIComponent(val)) : null;
} catch {
return null;
}
}
function getParamLegacy(name, url = window.location.href) {
// 正則:匹配 ?name=value 或 &name=value
const regex = new RegExp('[?&]' + name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '=([^&]*)');
const match = url.match(regex);
return match ? decodeURIComponent(match[1]) : null;
}
// 取得所有同名值
function getParamAllLegacy(name, url = window.location.href) {
const regex = new RegExp('[?&]' + name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '=([^&]*)', 'g');
const results = [];
let match;
while ((match = regex.exec(url)) !== null) {
results.push(decodeURIComponent(match[1]));
}
return results;
}
| 情境 | 問題 | 解決 |
|---|---|---|
| 中文參數 | URL 編碼為 %E4%B8%AD%E6%96%87 | URLSearchParams 自動解碼 |
| 空格 | 編碼為 + 或 %20 | 自動處理 |
| 特殊符號 & = # | 需編碼否則截斷 | 設定時用 encodeURIComponent |
| 雙重編碼 | 後端雙重 encode | 前端雙重 decodeURIComponent |
function updateURL(filters) {
const params = new URLSearchParams();
Object.entries(filters).forEach(([k, v]) => {
if (v !== null && v !== undefined && v !== '') {
if (Array.isArray(v)) v.forEach(val => params.append(k, val));
else params.set(k, v);
}
});
history.replaceState(null, '', `${location.pathname}?${params}`);
}
// 使用
updateURL({ page: 2, tag: ['js', 'vue'], sort: 'desc' });
// URL 變為 ?page=2&tag=js&tag=vue&sort=desc
function hydrateFormFromURL(formSelector) {
const params = getQueryParams();
const form = document.querySelector(formSelector);
for (const [key, value] of params) {
const input = form.querySelector(`[name="${key}"]`);
if (!input) continue;
if (input.type === 'checkbox') {
input.checked = value === 'true' || value === '1';
} else if (input.type === 'radio') {
const radio = form.querySelector(`[name="${key}"][value="${value}"]`);
if (radio) radio.checked = true;
} else if (input.multiple) {
// select multiple: 需 getAll
const values = params.getAll(key);
Array.from(input.options).forEach(opt => opt.selected = values.includes(opt.value));
} else {
input.value = value;
}
}
}
const UTM_KEYS = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'];
function captureUTM() {
const params = getQueryParams();
const utm = {};
UTM_KEYS.forEach(key => {
const val = params.get(key);
if (val) utm[key] = val;
});
if (Object.keys(utm).length) {
localStorage.setItem('utm_params', JSON.stringify(utm));
}
return utm;
}
interface QueryParams {
get(key: string): string | null;
getAll(key: string): string[];
has(key: string): boolean;
toObject(): Record;
toArray(): [string, string][];
}
class TypedQueryParams implements QueryParams {
constructor(private params: URLSearchParams) {}
get(key: string) { return this.params.get(key); }
getAll(key: string) { return this.params.getAll(key); }
has(key: string) { return this.params.has(key); }
toObject() { return Object.fromEntries(this.params); }
toArray() { return [...this.params]; }
// 型別安全取值
getString(key: string, fallback = '') { return this.get(key) ?? fallback; }
getNumber(key: string, fallback = 0) { return Number(this.get(key)) ?? fallback; }
getBoolean(key: string, fallback = false) {
const v = this.get(key);
return v === 'true' || v === '1' ? true : v === 'false' || v === '0' ? false : fallback;
}
getEnum(key: string, values: T[], fallback: T): T {
const v = this.get(key);
return values.includes(v as T) ? v as T : fallback;
}
}
// 使用
const qp = new TypedQueryParams(getQueryParams());
const page = qp.getNumber('page', 1);
const sort = qp.getEnum('sort', ['asc', 'desc'], 'asc');
new URLSearchParams(location.search) 可直接處理#/page?id=1 需用 new URLSearchParams(location.hash.split('?')[1])?foo= → get('foo') === '' (空字串非 null)?id=1&id=2 → get('id') === '1'、getAll('id') === ['1','2']現代專案請直接使用 URLSearchParams,它是標準、高效、自動處理編碼。封裝型別轉換方法 (getNumber, getBoolean) 能避免字串比較 Bug。舊專案相容可用正則 fallback,但新代碼無理由不使用標準 API。