The constructor takes a url parameter, and an optional base parameter to use as a base if the url parameter is a relative URL.
Note that in the case below "dogs" is the filename segment (because it has no trailing slash), and the relative URL "cats" is interpreted relative to the directory part of the base URL, which is http://www.example.com/animals/. See Resolving relative references to a URL for more information.
js
const url = new URL("cats", "http://www.example.com/animals/dogs");
console.log(url.hostname); // "www.example.com"
console.log(url.pathname); // "/animals/cats"
The constructor will raise an exception if the URL cannot be parsed to a valid URL.
You can either call the above code in a try...catch block or use the canParse() static method to first check the URL is valid:
js
if (URL.canParse("cats", "http://www.example.com/animals/dogs")) {
const url = new URL("cats", "http://www.example.com/animals/dogs");
console.log(url.hostname); // "www.example.com"
console.log(url.pathname); // "/animals/cats"
} else {
console.log("Invalid URL");
}
URL properties can be set to construct the URL:
js
url.hash = "tabby";
console.log(url.href); // "http://www.example.com/animals/cats#tabby"
URLs are encoded according to the rules found in RFC 3986. For instance:
js
url.pathname = "démonstration.html";
console.log(url.href); // "http://www.example.com/d%C3%A9monstration.html"
The URLSearchParams interface can be used to build and manipulate the URL query string.
To get the search params from the current window's URL, you can do this:
js
// https://some.site/?id=123
const parsedUrl = new URL(window.location.href);
console.log(parsedUrl.searchParams.get("id")); // "123"
The toString() method of URL just returns the value of the href property, so the constructor can be used to normalize and encode a URL directly.
js
const response = await fetch(
new URL("http://www.example.com/démonstration.html"),
);