DIV CSS 佈局教程網

JavaScript 與 jQuery 取得網址參數:正則、URLSearchParams 與外掛擴充
編輯:JavaScript綜合知識     

取得網址列(URL)與其查詢參數是前端最日常的任務之一。本文從原生做法談到 jQuery 擴充,最後給出現代寫法。

一、取得完整 URL

window.location.href;

這其實只是 JavaScript 的 window 物件,與 jQuery 無關。相關常用屬性:

location.href     完整網址
location.search   查詢字串(含 ?)
location.hash     錨點(含 #)
location.pathname 路徑部分
location.hostname 主機名稱

二、純 JavaScript 取得單一參數

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,否則中文或含特殊符號的參數會是亂碼。

三、擴充成 jQuery 靜態方法

(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)覆蓋時出錯。

四、現代寫法:URLSearchParams

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()。
  • 警惕 XSS:把 URL 參數直接寫進 innerHTML 或 document.write 是常見漏洞來源,請用 textContent。
  • 不要用參數做權限判斷:前端參數可被任意竄改,權限控管必須在後端。
  • hash 中的參數:location.search 只包含 ? 後的部分。若參數在 # 之後(常见于 hash 路由),需另外解析 location.hash。

總結:理解正則做法有助於掌握原理與維護舊專案,但新專案請直接用 URLSearchParams——更短、更安全、邊界情況都有規格保證。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved