在 Web 開發中,取得當前網址或其各個組成部分是很常見的需求。本文先解析 URL 的結構,再逐一示範如何以 JavaScript 取得每一個部分。
一個完整的 URL 由以下部分構成:
scheme://host:port/path?query#fragment
・scheme:通訊協定,常見的有 http、ftp、mailto 等。
・host:主機,即伺服器的網域名稱或 IP。
・port:連接埠,整數,可省略(省略時使用預設埠,如 http 為 80)。
・path:路徑,由「/」分隔的字串,表示主機上的目錄或檔案位址。
・query:查詢,可選,用於向動態網頁傳遞參數,多個參數以「&」分隔、名值以「=」分隔。
・fragment:資訊片段(又稱錨點),用於定位網路資源中的某一片段。
以下以 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
var test = window.location.port;
alert(test); // 若使用預設 80 埠,回傳值為空字串
var test = window.location.pathname;
alert(test); // /newsDetail.php
var test = window.location.search;
alert(test); // ?id=65
var test = window.location.hash;
alert(test); // #fragment
透過 window.location 的這些屬性,就能精準取得 URL 的每個組成部分。若需解析查詢參數為鍵值對,可搭配 URLSearchParams(如 new URLSearchParams(location.search).get('id')),比手動 split 更簡潔可靠。