返回

JavaScript URL 对象,解密操作 URL 的妙招

前端

JavaScript URL 对象简介

URL 对象是 JavaScript 中表示 URL(统一资源定位符)的类。它提供了一系列方法和属性,用于解析、编码和解码 URL 字符串。URL 对象可以通过两种方式创建:

  • 使用 new URL() 构造函数创建一个新的 URL 对象。
  • 使用 window.location 对象获取当前页面的 URL。

URL 对象的基本方法

URL 对象提供了许多有用的方法,用于解析和操作 URL。以下是一些最常用的方法:

  • toString(): 返回 URL 的字符串表示形式。
  • getOrigin(): 返回 URL 的源,包括协议、主机和端口。
  • getProtocol(): 返回 URL 的协议,例如 "http" 或 "https"。
  • getHost(): 返回 URL 的主机,例如 "www.example.com"。
  • getPort(): 返回 URL 的端口,如果没有端口,则返回空字符串。
  • getPathname(): 返回 URL 的路径,例如 "/path/to/file.html"。
  • getSearch(): 返回 URL 的查询字符串,例如 "?query=string"。
  • getHash(): 返回 URL 的哈希值,例如 "#fragment"。

URL 对象的基本属性

URL 对象还提供了一些有用的属性,用于获取和设置 URL 的不同部分。以下是一些最常用的属性:

  • href: URL 的字符串表示形式。
  • origin: URL 的源,包括协议、主机和端口。
  • protocol: URL 的协议,例如 "http" 或 "https"。
  • host: URL 的主机,例如 "www.example.com"。
  • port: URL 的端口,如果没有端口,则返回空字符串。
  • pathname: URL 的路径,例如 "/path/to/file.html"。
  • search: URL 的查询字符串,例如 "?query=string"。
  • hash: URL 的哈希值,例如 "#fragment"。

URL 对象的使用实例

以下是一些使用 URL 对象的实例:

  • 解析 URL:
const url = new URL('https://www.example.com/path/to/file.html?query=string#fragment');

console.log(url.protocol); // "https:"
console.log(url.host); // "www.example.com"
console.log(url.pathname); // "/path/to/file.html"
console.log(url.search); // "?query=string"
console.log(url.hash); // "#fragment"
  • 编码和解码 URL 字符串:
const url = 'https://www.example.com/path/to/file.html?query=string#fragment';

// 编码 URL 字符串
const encodedUrl = encodeURI(url);

// 解码 URL 字符串
const decodedUrl = decodeURI(encodedUrl);

console.log(encodedUrl); // "https://www.example.com/path/to/file.html?query=string%23fragment"
console.log(decodedUrl); // "https://www.example.com/path/to/file.html?query=string#fragment"
  • 创建新的 URL:
const url = new URL('https://www.example.com');

// 设置 URL 的不同部分
url.protocol = 'http';
url.host = 'www.google.com';
url.pathname = '/search';
url.search = '?q=javascript';

// 获取 URL 的字符串表示形式
const newUrl = url.toString();

console.log(newUrl); // "http://www.google.com/search?q=javascript"

结论

JavaScript URL 对象是一个非常有用的工具,可以用于操作 URL。它提供了许多方法和属性,可以轻松地解析、编码和解码 URL 字符串,甚至可以创建新的 URL。希望本文对您有所帮助。