How do you parse a URL with the URL API?
The URL constructor takes a string and gives you an object where the parts of the address have already been separated for you. You read each part from a named property instead of splitting the string yourself.
var 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 part of the object.
url.searchParams.set('page', '3');
console.log(url.search); // '?tab=api&page=3'
The searchParams property is the part that saves you 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, walk through them with the entries method, and add or remove them without touching the query string by hand. Because it is a live view of the URL, any change you make to it updates the URL object straight away.
There are two details about encoding that are worth knowing. The values in a query string are percent encoded, so a value with a space or an ampersand in it is stored in a safe form and comes back decoded when you use get, which does that decoding for you. And the whole address is normalised for you, so a URL with a missing scheme or a doubled slash is tidied up into its usual form.
The other reason to use the API instead of splitting strings is that it handles the awkward cases correctly. IPv6 hosts, ports with a default value, and paths that contain encoded characters are all parsed properly, where a regular expression would need a special case for each of them.