URL:pathname 屬性
注意:此功能在 Web Workers 中可用。
URL 介面的 pathname 屬性表示層次結構中的一個位置。它是一個由路徑段列表組成的字串,每個路徑段都以 / 字元為字首。
HTTPS、HTTP 或其他具有 分層方案(URL 標準稱之為“特殊方案”)的 URL 始終至少有一個(不可見的)路徑段:空字串。因此,此類 URL 的 pathname 值將始終至少包含一個 / 字元。
對於非分層方案,pathname 被稱為不透明路徑(意味著 URL 解析器不會嘗試將其拆分為段列表)。在這種情況下,空路徑將導致 pathname 屬性為空字串。如果不透明路徑的 hash 和 search 都為空,則在初始解析期間會刪除尾部空格;否則,即使稍後將 hash 和 search 設定為空字串,它們也會被百分比編碼為 %20。
注意:不透明路徑中百分比編碼尾部空格的實現並不廣泛。某些瀏覽器實現了舊的行為,即在 hash 和 search 屬性都為空字串時,從 pathname 中刪除尾部空格。在這些瀏覽器中,設定 hash 或 search 也可能改變 pathname。在更早的瀏覽器中,在刪除 hash 和 search 後,尾部空格仍然存在,導致序列化和解析無法進行往返。
值
字串。
示例
帶不可見段的 pathname
下面的 URL 只有一個路徑段,即空字串。pathname 值是透過在空字串前新增 / 字元來構造的。
const url = new URL("https://mdn.club.tw");
console.log(url.pathname); // Logs "/"
帶查詢引數的 pathname
下面的示例顯示了帶查詢引數的 HTTPS URL 的 pathname。
const url = new URL(
"https://mdn.club.tw/en-US/docs/Web/API/URL/pathname?q=value",
);
console.log(url.pathname); // Logs "/en-US/docs/Web/API/URL/pathname"
查詢引數不構成路徑的一部分。請注意,某些系統使用 ; 和 = 字元來分隔適用於路徑段的引數和引數值。例如,對於 URL https://example.org/users;id=42/tasks;state=open?sort=modified,系統可能會從路徑段 users;id=42 和 tasks;state=open 中提取並使用路徑段引數 id=42 和 state=open。
帶 slug 的 pathname
一些系統將slug 定義為非空路徑的最後一個段,如果它以人類可讀的關鍵字標識頁面。例如,下面的 URL 的 slug 是 this-that-other-outre-collection。
const url = new URL(
"https://example.org/articles/this-that-other-outre-collection",
);
console.log(url.pathname); // Logs "/articles/this-that-other-outre-collection"
帶不透明路徑的 pathname
當 URL 使用非分層方案時,pathname 屬性的行為略有不同。以下示例顯示了一個完全沒有路徑的 data: URL,在這種情況下,pathname 為空字串。
const url = new URL("data:");
console.log(JSON.stringify(url.pathname)); // ""
在初始解析期間,如果不存在 hash 或 search,瀏覽器總是會從 pathname 中刪除尾部空格。
const url = new URL("data:text/plain,Hello ");
console.log(JSON.stringify(url.pathname)); // "text/plain,Hello"
但是,如果在初始解析期間 hash 或 search 不為空,則尾部空格要麼被保留(舊行為),要麼被百分比編碼(新行為)。
const url = new URL("data:text/plain,Hello #frag");
console.log(JSON.stringify(url.pathname)); // "text/plain,Hello " (old) or "text/plain,Hello%20" (new)
如果它們稍後被設定為空字串,尾部空格要麼被刪除(舊行為),要麼保持百分比編碼(新行為)。
const url = new URL("data:text/plain,Hello #frag");
url.hash = "";
console.log(JSON.stringify(url.pathname)); // "text/plain,Hello" (old) or "text/plain,Hello%20" (new)
這兩種行為都確保了 URL 的序列化和解析能夠進行往返;也就是說,new URL(url.href).href 始終等於 url.href。如果移除 hash 後尾部空格保持不變,那麼 new URL() 會將其刪除。
規範
| 規範 |
|---|
| URL # dom-url-pathname |
瀏覽器相容性
載入中…
另見
- 它所屬的
URL介面。