DIV CSS 佈局教程網

JavaScript 獲取 URL 各部分的完整方法彙總
編輯:JavaScript綜合知識     

在 Web 開發中,取得當前網址或其各個組成部分是很常見的需求。本文先解析 URL 的結構,再逐一示範如何以 JavaScript 取得每一個部分。

URL 的組成結構

一個完整的 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 為例:

整個 URL:window.location.href

var test = window.location.href;
alert(test);   // https://www.jb51.net/newsDetail.php?id=65

協定:window.location.protocol

var test = window.location.protocol;
alert(test);   // http:

主機:window.location.host

var test = window.location.host;
alert(test);   // www.jb51.net

連接埠:window.location.port

var test = window.location.port;
alert(test);   // 若使用預設 80 埠,回傳值為空字串

路徑:window.location.pathname

var test = window.location.pathname;
alert(test);   // /newsDetail.php

查詢(參數):window.location.search

var test = window.location.search;
alert(test);   // ?id=65

錨點:window.location.hash

var test = window.location.hash;
alert(test);   // #fragment

補充

透過 window.location 的這些屬性,就能精準取得 URL 的每個組成部分。若需解析查詢參數為鍵值對,可搭配 URLSearchParams(如 new URLSearchParams(location.search).get('id')),比手動 split 更簡潔可靠。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved