URL 參數解析是前端高頻剛需。本文演進展示:原生正則解析 → jQuery 擴展插件 → 現代 URLSearchParams 原生 API,並對比性能與兼容性。
function getUrlParam(name) {
// 構造正則:匹配 ?key=value& 或 &key=value& 或 ?key=value$
var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
// location.search 返回 "?cid=79&page=1",substr(1) 去掉 ?
var match = window.location.search.substr(1).match(reg);
return match ? decodeURIComponent(match[2]) : null;
}
// 使用
var cid = getUrlParam('cid'); // URL: ?cid=79 → "79"
(function($) {
$.getUrlParam = function(name) {
var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
var match = window.location.search.substr(1).match(reg);
return match ? decodeURIComponent(match[2]) : null;
};
})(jQuery);
// 使用
$.getUrlParam('cid');
// 1. 當前頁面 URL
const params = new URLSearchParams(window.location.search);
console.log(params.get('cid')); // 單值
console.log(params.getAll('tag')); // 多值 ['a','b']
console.log(params.has('page')); // boolean
params.forEach((val, key) => console.log(key, val)); // 遍歷
// 2. 任意 URL 字符串解析
const url = 'https://example.com/path?a=1&b=2&b=3#hash';
const urlObj = new URL(url); // URL 對象解析完整 URL
console.log(urlObj.searchParams.get('b')); // "2" (首個)
console.log(urlObj.searchParams.getAll('b')); // ["2", "3"]
// 3. 構建/修改 URL
const sp = new URLSearchParams();
sp.append('key', 'value');
sp.set('key', 'newValue');
sp.delete('key');
sp.toString(); // "key=newValue"
// 4. 表單提交直接構建
const formData = new FormData(formElement);
const params = new URLSearchParams(formData);
fetch('/api', {method: 'POST', body: params});
// 統一入口:優先原生,降級正則
window.getQueryParam = (function() {
if (typeof URLSearchParams !== 'undefined') {
return function(name, url) {
var search = url ? new URL(url).search : window.location.search;
return new URLSearchParams(search).get(name);
};
}
// 降級正則實現
return function(name, url) {
var search = url ? url.split('?')[1] : window.location.search.substr(1);
var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
var match = search.match(reg);
return match ? decodeURIComponent(match[2]) : null;
};
})();
// 使用:完全一致的 API
getQueryParam('cid');
getQueryParam('cid', 'https://example.com?cid=99');
// 原生 URL API (IE 不支持)
const url = new URL('https://user:pass@example.com:8080/path?query=1#hash');
console.log(url.protocol); // "https:"
console.log(url.host); // "example.com:8080"
console.log(url.hostname); // "example.com"
console.log(url.port); // "8080"
console.log(url.pathname); // "/path"
console.log(url.search); // "?query=1"
console.log(url.hash); // "#hash"
console.log(url.username); // "user"
console.log(url.password); // "pass"
console.log(url.origin); // "https://example.com:8080"
| 方法 | 耗時 (ms) | 備註 |
|---|---|---|
| URLSearchParams | ~45 | 原生 C++ 實現,最快 |
| 正則 match | ~120 | 需編譯正則,可緩存 RegExp 提升 |
| split + 循環 | ~200 | 字符串操作開銷大 |
URLSearchParams + URL,配合 core-js polyfill 兼容 IE。new URLSearchParams(location.search) 實例。URL 對象,手寫正則極易出錯。# % & =) 必須 encodeURIComponent 編碼,解析時 decodeURIComponent。