URL:pathname 属性

Baseline 已广泛支持

此特性已非常成熟,可在多种设备和浏览器版本上使用。自 ⁨2016 年 9 月⁩以来,它已在各大浏览器中可用。

注意:此功能在 Web Workers 中可用。

URL 接口的 pathname 属性表示层次结构中的一个位置。它是一个由路径段列表组成的字符串,每个路径段都以 / 字符为前缀。

HTTPS、HTTP 或其他具有 分层方案(URL 标准称之为“特殊方案”)的 URL 始终至少有一个(不可见的)路径段:空字符串。因此,此类 URL 的 pathname 值将始终至少包含一个 / 字符。

对于非分层方案,pathname 被称为不透明路径(意味着 URL 解析器不会尝试将其拆分为段列表)。在这种情况下,空路径将导致 pathname 属性为空字符串。如果不透明路径的 hashsearch 都为空,则在初始解析期间会删除尾部空格;否则,即使稍后将 hashsearch 设置为空字符串,它们也会被百分比编码为 %20

注意:不透明路径中百分比编码尾部空格的实现并不广泛。某些浏览器实现了旧的行为,即在 hashsearch 属性都为空字符串时,从 pathname 中删除尾部空格。在这些浏览器中,设置 hashsearch 也可能改变 pathname。在更早的浏览器中,在删除 hash 和 search 后,尾部空格仍然存在,导致序列化和解析无法进行往返

字符串。

示例

带不可见段的 pathname

下面的 URL 只有一个路径段,即空字符串。pathname 值是通过在空字符串前添加 / 字符来构造的。

js
const url = new URL("https://mdn.org.cn");
console.log(url.pathname); // Logs "/"

带查询参数的 pathname

下面的示例显示了带查询参数的 HTTPS URL 的 pathname。

js
const url = new URL(
  "https://mdn.org.cn/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=42tasks;state=open 中提取并使用路径段参数 id=42state=open

带 slug 的 pathname

一些系统将slug 定义为非空路径的最后一个段,如果它以人类可读的关键字标识页面。例如,下面的 URL 的 slug 是 this-that-other-outre-collection

js
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 为空字符串。

js
const url = new URL("data:");
console.log(JSON.stringify(url.pathname)); // ""

在初始解析期间,如果不存在 hash 或 search,浏览器总是会从 pathname 中删除尾部空格。

js
const url = new URL("data:text/plain,Hello ");
console.log(JSON.stringify(url.pathname)); // "text/plain,Hello"

但是,如果在初始解析期间 hash 或 search 不为空,则尾部空格要么被保留(旧行为),要么被百分比编码(新行为)。

js
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)

如果它们稍后被设置为空字符串,尾部空格要么被删除(旧行为),要么保持百分比编码(新行为)。

js
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 接口。