Web API 之 — URL API

URL API 是浏览器根据 Whatwg 的标准[https://url.spec.whatwg.org/]实现的一组 API。通常自己去写正则或循环去解析 URL 时,很难考虑全各种边边角角的问题,导致意想不到的错误。而有了这组 API,就可以方便准确地进行 URL 解析了。

URL 的组成

URL 的规范可以查看 ietf 的标准[https://tools.ietf.org/html/rfc3986],这里就简单说明一下其组成。

拿这个例子来看:http://www.example.com:8080/path/to/myfile.html?key1=value1&key2=value2#SomewhereInTheDocument从前往后依次是

  • protocol 协议,http:
  • domain name 域名,www.example.com
  • port 端口,8080
  • path 路径,/path/to/myfile.html
  • parameters 参数,?key1=value1&key2=value2
  • anchor 锚点,#SomewhereInTheDocument

简单使用

URL API 的基本用法就把一个 url 的各部分都解析出来。如下:

let u = new URL('http://user

你可能感兴趣的:(Web,API,browser,前端)