创建URL对象实例
const url = new URL('https://www.example.com/path?query=value#hash');
得到
URL {
href: 'https://www.example.com/path?query=value#hash',
origin: 'https://www.example.com',
protocol: 'https:',
username: '',
password: '',
host: 'www.example.com',
hostname: 'www.example.com',
port: '',
pathname: '/path',
search: '?query=value',
searchParams: URLSearchParams { 'query' => 'value' },
hash: '#hash'
}
可便捷获取和修改 URL 的属性
console.log(url.host); // www.example.com
url.host = 'www.newexample.com';
console.log(url.href); // https://www.newexample.com/path?query=value#hash
参数对象 URLSearchParams
通过 URL 对象的 searchParams 属性可获取 参数对象 URLSearchParams
const url = new URL('https://www.example.com/path?query=value#hash');
const params = url.searchParams;
获取参数的值 get
params.get('query') // value
修改参数的值 set
params.set('page', '2')
编码 URL
使用 encodeURIComponent 方法来编码 URL 的查询参数
encodeURIComponent('hello world!') // hello%20world%21
解码 URL
使用decodeURIComponent方法来解码 URL 的查询参数
decodeURIComponent('hello%20world%21') // 'hello world!'