URL
Parses an address into parts and builds it back.
Available since: Web API
Syntax
new URL(url, base)Parameters
| Parameter | Type | Description |
|---|---|---|
| url | string | An address — absolute or relative. |
| base | string | Optional. The base address for a relative url. |
Return value
URLAn object with the parts of the address: protocol, hostname, pathname, searchParams and more.
Examples
The parts of an address:
const url = new URL('https://shop.example.com:8080/catalog/tea?page=2#reviews');
console.log(url.hostname);
console.log(url.pathname);
console.log(url.searchParams.get('page'));
console.log(url.hash);Output:
shop.example.com
/catalog/tea
2
#reviewsChanging parameters:
const url = new URL('https://example.com/search');
url.searchParams.set('q', 'green tea');
url.searchParams.set('sort', 'price');
console.log(url.href);Output:
https://example.com/search?q=green+tea&sort=priceA relative address and a validity check:
console.log(new URL('../img/logo.png', 'https://example.com/blog/post/').href);
console.log(URL.canParse('not a url'));Output:
https://example.com/blog/img/logo.png
falseNotes
An invalid address in new URL() throws a TypeError. You can check first with URL.canParse().
See also
- URLSearchParams — Reads and builds URL query parameters (the part after ?).
- encodeURIComponent — Encodes text for safely putting it into part of a URL.
- fetch — Sends an HTTP request and returns a promise of the response.
Related recipes
In the tutorial
- Server requests: fetch — The fetch function in JavaScript: GET and POST requests, the response object, status, response.ok, parsing JSON and handling errors.