URL (Uniform Resource Locator) 是统一资源定位符的缩写。每个 URL 都指向网络上一个唯一的资源,就像资源的门牌号一般。

let url = new URL("http://example.com:8080/index.html?id=10&page=2#target")

以上是一个 URL, 它由以下几部分组成:

  • 协议 protocol:http,浏览器与服务器交流时所用的语言(协议),比如还有 https,它是 http 的加密版本。
  • 主机名 hostname:example.com,浏览器可以用主机名(域名)去 DNS 确认域名对应的服务器 IP,根据 IP 就能找到服务器并与之通信。
  • 端口 port:8080,很多 URL 没有标明端口号,那么在 http 下它就是默认的 80,https 下就是默认的 443。
  • 路径 path:index.html,表示资源在服务器上的位置。
  • 参数字符串 search:id=10&page=2,请求携带的额外参数,用 & 分隔,它的意义由后端决定。
  • 锚部分 hash:#target,一般指向页面上某个资源的 id。

$$tip

更多 URL 相关细节可以看 URL - MDN

$$

URL 对象

JavaScript 中 URL 是一个处理 URL 专用的对象。

如下创建了一个 URL 对象:

let url = new URL("http://example.com:8080/index.html?id=10&page=2#target")

URL 对象有以下常用属性:

  • href:完整的 URL 字符串。
  • protocol:协议。
  • host:主机和端口。
  • hostname:主机名。
  • port:端口号。
  • search:查询字符串。
  • searchParams:URLSearchParams 对象,
  • hash:锚部分。
const url = new URL("http://example.com:8080/index.html?id=10&page=2#target")

console.log(url.href) // http://example.com:8080/index.html?id=10&page=2#target
console.log(url.protocol) // http:
console.log(url.host) // example.com:8080
console.log(url.hostname) // example.com
console.log(url.port) // 8080
console.log(url.search) // ?id=10&page=2
console.log(url.hash) // #target