在JavaScript中,URL对象用于解析、构建、修改和序列化URLs。它提供了一种方便的方式来处理URLs中的各个部分,比如协议、主机名、路径名、查询字符串等。
URL对象可以通过new URL()
构造函数创建,该构造函数接受两个参数:一个是URL字符串,另一个是可选的基URL字符串(用于解析相对URL)。
URL对象本身就是一个类型,它包含以下主要属性:
href
:完整的URL字符串。protocol
:URL的协议部分,包括末尾的冒号。hostname
:URL的主机名部分。port
:URL的端口号。pathname
:URL的路径名部分。search
:URL的查询字符串部分,包括开头的问号。searchParams
:一个URLSearchParams对象,用于处理查询字符串。hash
:URL的片段标识符部分,包括开头的井号。// 创建一个URL对象
const url = new URL('https://example.com/path?name=test#section');
// 访问URL的各个部分
console.log(url.protocol); // "https:"
console.log(url.hostname); // "example.com"
console.log(url.pathname); // "/path"
console.log(url.search); // "?name=test"
console.log(url.searchParams.get('name')); // "test"
console.log(url.hash); // "#section"
// 修改URL的某个部分
url.pathname = '/new-path';
url.searchParams.set('newParam', 'newValue');
console.log(url.href); // "https://example.com/new-path?name=test&newParam=newValue#section"
const baseUrl = 'https://example.com/';
const relativeUrl = '/path';
const url = new URL(relativeUrl, baseUrl);
console.log(url.href); // "https://example.com/path"
URLSearchParams
对象来方便地处理查询字符串。const url = new URL('https://example.com/path?name=test');
url.searchParams.append('age', '30');
console.log(url.href); // "https://example.com/path?name=test&age=30"
const url = new URL('https://example.com/search?q=hello world');
console.log(url.search); // "?q=hello%20world"
通过使用URL对象,可以更方便地处理和操作URLs,提高代码的可读性和可维护性。
领取专属 10元无门槛券
手把手带您无忧上云