window.location 是我們熟悉的物件,它有 protocol、hostname、host、port、search、hash、href、pathname 等屬性。有趣的是,用 JavaScript 建立的 a 元素也有完全相同的屬性集——只要把 href 設為某個網址,瀏覽器就會自動把它拆解填入各屬性。
這提供了一個優雅的解法:不必自己寫正則去切割 URL,交給瀏覽器就好。
function parseURL(url) {
var a = document.createElement('a');
a.href = url;
return {
source: url,
protocol: a.protocol.replace(':',''),
host: a.hostname,
port: a.port || '80',
query: a.search,
params: (function(){
var ret = {},
seg = a.search.replace(/^\?/,'').split('&'),
len = seg.length,
i = 0, s;
for (; i < len; i++) {
if (!seg[i]) { continue; }
s = seg[i].split('=');
ret[s[0]] = s[1];
}
return ret;
})(),
file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
hash: a.hash.replace('#',''),
path: a.pathname.replace(/^([^\/])/,'/$1'),
relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
segments: a.pathname.replace(/^\//,'').split('/')
};
}console.log(parseURL("https://www.w3school.com.cn/jsref/dom_obj_anchor.asp?type=2#id2"));輸出結果:
{
file: "dom_obj_anchor.asp",
hash: "id2",
host: "www.w3school.com.cn",
params: {type: "2"},
path: "/jsref/dom_obj_anchor.asp",
port: "80",
protocol: "http",
query: "?type=2",
relative: "/jsref/dom_obj_anchor.asp?type=2#id2",
segments: ["jsref", "dom_obj_anchor.asp"],
source: "https://www.w3school.com.cn/jsref/dom_obj_anchor.asp?type=2#id2"
}自己寫正則解析 URL 很容易漏掉邊界情況:使用者名稱與密碼(user:pass@host)、IPv6 位址、非預設連接埠、相對路徑、協議相對網址(//example.com)等等。交給瀏覽器的解析器,這些都由規格定義好的行為處理。
key 沒有等號的情況。要更嚴謹,用 URLSearchParams。/^([^\/])/ 只匹配「不是斜線開頭」的第一個字元,並用 /$1 取代——但 $1 只是那單一字元,其餘部分雖會保留在結果中(因為只有開頭被替換),寫法本身容易誤讀。更清楚的寫法是 a.pathname.charAt(0) === '/' ? a.pathname : '/' + a.pathname。今天更推薦用原生的 URL 建構子,它不需依賴 DOM,也能在 Node 與 Web Worker 中使用:
var u = new URL("https://www.w3school.com.cn/jsref/dom_obj_anchor.asp?type=2#id2");
console.log(u.hostname); // "www.w3school.com.cn"
console.log(u.pathname); // "/jsref/dom_obj_anchor.asp"
console.log(u.searchParams.get("type")); // "2"
console.log(u.hash); // "#id2"URL 物件功能更完整(有 username、password、origin、searchParams 等),且對編碼的處理符合標準。a 標籤這招的價值,在於理解「瀏覽器已經幫你解析好了」這個事實——在無法使用 URL 建構子的舊環境中,它是個實用的技巧。