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
#reviewsChanging 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=2A 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.pngCommon 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
trueFunctions used in this recipe
- URL — Parses an address into parts and builds it back.
- URLSearchParams — Reads and builds URL query parameters (the part after ?).