取得網址列(URL)與其查詢參數是前端最日常的任務之一。本文從原生做法談到 jQuery 擴充,最後給出現代寫法。
window.location.href;
這其實只是 JavaScript 的 window 物件,與 jQuery 無關。相關常用屬性:
location.href 完整網址 location.search 查詢字串(含 ?) location.hash 錨點(含 #) location.pathname 路徑部分 location.hostname 主機名稱
function getUrlParam(name) {
// 組出比對目標參數的正則
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg); // 去掉開頭的 ?
return (r != null) ? decodeURIComponent(r[2]) : null;
}
用法:
// 網址為 https://www.example.com/admin/write-post.php?cid=79
getUrlParam('cid'); // "79"
正則的拆解:(^|&) 確保 name 是參數開頭(避免 id 誤配 userid),([^&]*) 抓取到下一個 & 之前的所有字元,(&|$) 收尾。最後一定要 decodeURIComponent,否則中文或含特殊符號的參數會是亂碼。
(function ($) {
$.getUrlParam = function (name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
return (r != null) ? decodeURIComponent(r[2]) : null;
};
})(jQuery);
// 使用
$.getUrlParam('cid');
這裡用了 IIFE 並把 jQuery 傳入參數 $,是 jQuery 外掛的標準寫法,可避免全域 $ 被其他函式庫(如 Prototype)覆蓋時出錯。
ES2015 之後,上述所有工都不用自己寫了:
var params = new URLSearchParams(window.location.search);
params.get('cid'); // 單一參數值
params.getAll('tag'); // 同名參數全部值(陣列)
params.has('cid'); // 是否存在
params.append('page', '2'); // 新增
params.toString(); // 轉回查詢字串
// 也可以直接操作
var url = new URL(window.location.href);
url.searchParams.set('page', 3);
window.history.replaceState({}, '', url);
URLSearchParams 的優勢不只是短:它自動處理 URL 編碼解碼、正确处理同名參數、對 + 代表空白的規則也符合規格。自寫正則很容易在這些邊界情況上出錯。
decodeURIComponent(URLSearchParams 已內建)。getUrlParam('page') + 1 會得到 "21" 而非 3,需要時請显式 Number()。innerHTML 或 document.write 是常見漏洞來源,請用 textContent。location.search 只包含 ? 後的部分。若參數在 # 之後(常见于 hash 路由),需另外解析 location.hash。總結:理解正則做法有助於掌握原理與維護舊專案,但新專案請直接用 URLSearchParams——更短、更安全、邊界情況都有規格保證。