What is the URL web API?

The web keeps growing and getting more sophisticated. Due to this, more support is poured into the web, giving it the ability to do things native to the operating system. Such support includes the URL API.

URL API

The URL API is used to access and manipulate URLs.

Passing a URL into the new URL() object constructor will break the URL into its constituent parts: port, hostname, protocol, etc. These are parts of a URL.

All of the parts of a URL are:

  • hash
  • host
  • hostname
  • href
  • origin
  • pathname
  • port
  • protocol

  • # hash

This is where a hash (#) is placed in a URL. ​

example.com/page1/#example

For the URL above, the hash is #example.

const url = new URL("example.com/page1/#example")
url.hash // #example

  • # host

This is the domain name and the port number of the URL.

example.com:80/page1

The host is example.com:80

const url = new URL("example.com:80/page1")
url.host // example.com:80

  • # hostname

This is the domain name of the URL.

example.com:80/page1

example.com is the hostname.

const url = new URL("example.com:80/page1")
url.hostname // example.com

  • href

This is the full URL.

example.com:80/page1/#example

For the URL above, the href is example.com:80/page1/#example.

const url = new URL("example.com:80/page1/#example")
url.href // example.com:80/page1/#example

  • origin

This is the protocol of the URL, the domain name, and the port of the URL.

https://example.com:80/page1/#example

The origin of the URL above is https://example.com:80.

const url = new URL("https://example.com:80/page1/#example")
url.origin // [https://example.com:80/](https://example.com:80/)

  • pathname

This is the path of the URL after the domain name until the hash (if any).

https://example.com:80/page1/#example

For the above URL, the pathname is /page1/.

const url = new URL("https://example.com:80/page1/#example")
url.pathname // /page1/

  • port

This is the web port number from where the URL is located.

https://example.com:80/page1/#example

The port is 80.

const url = new URL("https://example.com:80/page1/#example")
url.port // 80

  • protocol

This is the HTTP where the URL is served from.

https://example.com:80/page1/#example

The protocol is https.

const url = new URL("https://example.com:80/page1/#example")
url.protocol // https:

Free Resources