先釐清名詞:URL 是 Uniform Resource Locator(統一資源定位符)的縮寫。一個完整的 URL 由以下幾塊拼成:
scheme://host:port/path?query#fragment
/ 分隔的字串組成,通常用來指向主機上的目錄或檔案。& 分隔,參數名與值之間以 = 分隔。以下用這個 URL 作為示範:
https://www.jb51.net/newsDetail.php?id=65
var test = window.location.href; alert(test); // https://www.jb51.net/newsDetail.php?id=65
var test = window.location.protocol; alert(test); // http:
注意回傳值帶有冒號。
var test = window.location.host; alert(test); // www.jb51.net
host 包含主機名稱與連接埠(若有明確指定);只要主機名的話用 window.location.hostname。
var test = window.location.port; alert(test);
若採用預設的 80 埠(即使網址列上明確寫了 :80),回傳值是空字串而非 "80"。
var test = window.location.pathname; alert(test); // /newsDetail.php
var test = window.location.search; alert(test); // ?id=65
除了給後端語言取用,靜態頁面同樣可以用 JavaScript 解析這段字串來取得參數值。
var test = window.location.hash; alert(test); // #section2
手動 split('&') 解析 query 已經是舊做法,現在直接用內建 API 就好:
const params = new URLSearchParams(location.search);
console.log(params.get('id')); // 65
console.log(params.has('keyword')); // false
// 也可以解析完整的 URL
const u = new URL('https://www.jb51.net/newsDetail.php?id=65');
console.log(u.hostname, u.pathname, u.searchParams.get('id'));
順帶一提,location.hash 的變化不會重新載入頁面,這正是早期 hash 路由(#/user/1)能運作的基礎。