How do you parse a URL with the URL API?
The URL constructor takes a string and gives you an object with the parts already broken out. You read them from named properties rather than parsing the string yourself.
const url = new URL("https://user:[email protected]:8443/docs/guide?tab=api&page=2#section");
console.log(url.protocol); // "https:"
console.log(url.hostname); // "example.com"
console.log(url.port); // "8443"
console.log(url.pathname); // "/docs/guide"
console.log(url.searchParams.get("tab")); // "api"
console.log(url.hash); // "#section"
console.log(url.origin); // "https://example.com:8443"
// The search parameters are a live API.
url.searchParams.set("page", "3");
console.log(url.search); // "?tab=api&page=3"The searchParams property is the part that saves the most time. It is a full URLSearchParams object, so you can read a single parameter with the get method, check for one with has, iterate over them with the entries method, and add or remove them without touching the query string by hand. Because it is a live view, changing it updates the URL object straight away.
Two details about encoding. Values in a query string are percent encoded, so a value with a space or an ampersand in it comes back decoded when you use get, and the get method decodes it for you. And the whole thing is normalised for you, so a URL with a missing scheme or a doubled slash is tidied up into its canonical form.
The other reason to use the API rather than string splitting is that it handles the awkward cases correctly. IPv6 hosts, ports with a default value, and paths with encoded characters all get parsed properly, where a regular expression would need a special case for each of them.