URL类
URL类,在全局对象上,node和浏览器,都可以直接访问
new URL('https://www.baidu.com') // 解析url地址的各种属性
/*
{
href: 'https://www.baidu.com/',
origin: 'https://www.baidu.com',
protocol: 'https:',
username: '',
password: '',
host: 'www.baidu.com',
hostname: 'www.baidu.com',
port: '',
pathname: '/',
search: '',
searchParams: URLSearchParams {},
hash: ''
}
*/
// 旧版本
const url = require('url')
url.parse('https://www.baidu.com')
URL相比require('url'),URL具有数据劫持的功能
const myURL = new URL('https://example.org/foo#bar');
myURL.hash = 'baz';
console.log(myURL.href); // 打印 https://example.org/foo#baz
URLSearchParams
const myURL = new URL('https://example.org/?abc=123');
console.log(myURL.searchParams.get('abc'));
// 打印 123
myURL.searchParams.append('abc', 'xyz');
console.log(myURL.href);
// 打印 https://example.org/?abc=123&abc=xyz
myURL.searchParams.delete('abc');
myURL.searchParams.set('a', 'b');
console.log(myURL.href);
// 打印 https://example.org/?a=b
const newSearchParams = new URLSearchParams(myURL.searchParams);
// 以上相当于
// const newSearchParams = new URLSearchParams(myURL.search);
newSearchParams.append('a', 'c');
console.log(myURL.href);
// 打印 https://example.org/?a=b
console.log(newSearchParams.toString());
// 打印 a=b&a=c
// newSearchParams.toString() 是隐式调用的
myURL.search = newSearchParams;
console.log(myURL.href);
// 打印 https://example.org/?a=b&a=c
newSearchParams.delete('a');
console.log(myURL.href);
// 打印 https://example.org/?a=b&a=c
网友评论