创建URL对象实例

const url = new URL('https://www.example.com/path?query=value#hash');
  • 1.

得到

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'
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.

可便捷获取和修改 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
  • 1.
  • 2.
  • 3.
  • 4.

参数对象 URLSearchParams

通过 URL 对象的 searchParams 属性可获取 参数对象 URLSearchParams

const url = new URL('https://www.example.com/path?query=value#hash');
const params = url.searchParams;
  • 1.
  • 2.

获取参数的值 get

params.get('query') // value
  • 1.

修改参数的值 set

params.set('page', '2')
  • 1.

编码 URL

使用 encodeURIComponent 方法来编码 URL 的查询参数

encodeURIComponent('hello world!') // hello%20world%21
  • 1.

解码 URL

使用decodeURIComponent方法来解码 URL 的查询参数

decodeURIComponent('hello%20world%21') // 'hello world!'
  • 1.