要在前端讀取網址上的查詢參數,最直覺的做法是用正則運算式從 location.search 中擷取。以下是常見的封裝寫法。
/**
* 獲取地址欄參數
*
* @example GetUrlString('id')
*
* @param String param 要獲取的參數名
* @return String Value
* @name GetUrlString()
*/
function GetUrlString(param) {
var sValue = location.search.match(new RegExp("[?&]" + param + "=([^&]*)(&?)", "i"));
return sValue ? decodeURIComponent(sValue[1]) : "";
}
如果網址是 abc.html 而後面完全沒有參數,直接輸出呼叫結果在某些情況下會報錯。建議統一養成先檢查再使用的習慣:
window.onload = function() {
var myurl = GetParm("id");
if (myurl != null && myurl.toString().length > 1) {
alert(GetParm("id"));
}
};
原始範例中用 decodeURI() 解碼,但查詢參數的值應該使用 decodeURIComponent()。兩者的差別在於:decodeURI() 不會解碼 &、=、? 這類保留字元,而這些字元在參數值中被編碼後(如 %26)恰恰是需要還原的。ECMAScript v3 已將 unescape() 從標準中移除並不建議使用,應以 decodeURIComponent() 取代。
另外,若無參數時回傳 "" 而非空字串以外的值,判斷式就可以簡化為 if (myurl)。而 decodeURIComponent() 遇到格式錯誤的編碼(例如單獨一個 %)會丟出 URIError,正式環境建議包在 try-catch 裡。
現在不需要自己寫正則了,瀏覽器內建的 URLSearchParams 就能搞定,而且自動處理解碼與重複參數:
const params = new URLSearchParams(location.search);
const id = params.get("id"); // 取單一參數,不存在則為 null
const all = params.getAll("tag"); // 取同名參數的全部值,回傳陣列
const has = params.has("token"); // 判斷是否存在
這個 API 相容性良好,程式碼更短、意圖更清楚,也不會有自己寫正則時容易忽略的邊界情況,新專案建議直接採用。