從網址列抓參數是前端最日常的任務之一。實務上有兩條路:用正則表達式精準比對,或是以字串切割的方式逐段拆解。本文兩種都示範,並附上 window.location 各屬性的對照說明。
function GetQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]);
return null;
}
alert(GetQueryString("id"));
正則的關鍵在兩端錨點:(^|&) 確保參數名是開頭或緊接在 & 之後,避免把 user_id 誤抓成 id;([...]*)(&|$) 則確保取值到下一個分隔符或字串結尾為止。
以 abc.html?id=123&url=https://www.example.com 為例:
GetQueryString("url"); // "https://www.example.com"
GetQueryString("id"); // "123"
如果網址後完全沒有參數,強制取用可能出問題,因此務必先判空:
var myurl = GetQueryString("url");
if (myurl != null && myurl.toString().length > 1) {
alert(myurl);
}
另外提醒兩點:unescape 已屬舊 API,遇到中文或特殊字元時建議改用 decodeURIComponent;參數名若可能包含正則元字元,需先做轉義處理。
function UrlSearch() {
var name, value;
var str = location.href;
var num = str.indexOf("?");
str = str.substr(num + 1); // 取出問號後的所有參數
var arr = str.split("&"); // 各個參數放進陣列
for (var i = 0; i < arr.length; i++) {
num = arr[i].indexOf("=");
if (num > 0) {
name = arr[i].substring(0, num);
value = arr[i].substr(num + 1);
this[name] = value; // 掛成物件屬性
}
}
}
var Request = new UrlSearch();
alert(Request.id);
把檔案存成 1.html,訪問 1.html?id=test 時就能取到 test。這種寫法的好處是一次解析後可以用屬性存取任意參數,缺點是遇到網址沒有問號時 indexOf 回傳 -1,需要額外處理。
回傳從指定位置開始、指定長度的子字符串。
順帶一提相關字串方法:str.toLowerCase() 轉小寫、str.toUpperCase() 轉大寫。
完整的 URL 格式為:scheme://host:port/path?query#fragment
& 分隔,名稱與值以 = 分隔。以 https://www.example.com/index.html?ver=1.0&id=6#imhere 為例:
window.location.href → 完整網址 https://www.example.com/index.html?ver=1.0&id=6#imherewindow.location.protocol → http:window.location.host → www.example.comwindow.location.port → 空字符串(採用預設 80 時即使寫了 :80 也回傳空)window.location.pathname → /index.htmlwindow.location.search → ?ver=1.0&id=6window.location.hash → #imhere如果不是要支援老舊環境,直接用 URLSearchParams 會乾淨很多:
var params = new URLSearchParams(location.search);
params.get('id'); // "123"
params.has('url'); // true / false
params.getAll('tag'); // 同名參數的陣列
params.toString(); // 重新序列化為查詢字串
它會自動處理編碼解碼、重複參數與空值判斷,是目前讀取查詢參數的首選。