Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to parse a URL into parts

Short answer

The URL object splits an address into parts:

const url = new URL('https://shop.example.com:8080/catalog/tea?sort=price#reviews');
 
console.log(url.protocol);
console.log(url.hostname);
console.log(url.port);
console.log(url.pathname);
console.log(url.searchParams.get('sort'));
console.log(url.hash);

Output:

https:
shop.example.com
8080
/catalog/tea
price
#reviews

Changing an address

Parts of a URL can be changed, and href returns the updated address:

const url = new URL('https://example.com/search?q=tea');
url.searchParams.set('q', 'green tea');
url.searchParams.set('page', '2');
 
console.log(url.href);

Output:

https://example.com/search?q=green+tea&page=2

A relative address

The second argument is the base address. That way relative links become full ones:

console.log(new URL('../images/logo.png', 'https://example.com/blog/post/').href);

Output:

https://example.com/blog/images/logo.png

Common mistake

new URL() throws an error for an incomplete address. Check it with URL.canParse() first:

console.log(URL.canParse('example.com/page'));
console.log(URL.canParse('https://example.com/page'));

Output:

false
true

Functions used in this recipe

  • URL — Parses an address into parts and builds it back.
  • URLSearchParams — Reads and builds URL query parameters (the part after ?).

Thanks for reading!

Donate to the site — we work hard for you.