The built-in URL class provides a convenient interface for creating and parsing URLs.
There are no networking methods that require exactly a URL object, strings are good enough. So technically we don’t have to use URL. But sometimes it can be really helpful.
Creating a URL
The syntax to create a new URL object:
new URL(url, [base])
url– the full URL or only path (if base is set, see below),base– an optional base URL: if set andurlargument has only path, then the URL is generated relative tobase.
For example:
let url = new URL('https://javascript.info/profile/admin');
These two URLs are same:
let url1 = new URL('https://javascript.info/profile/admin');
let url2 = new URL('/profile/admin', 'https://javascript.info');
alert(url1); // https://javascript.info/profile/admin
alert(url2); // https://javascript.info/profile/admin
We can easily create a new URL based on the path relative to an existing URL:
let url = new URL('https://javascript.info/profile/admin');
let newUrl = new URL('tester', url);
alert(newUrl); // https://javascript.info/profile/tester
The URL object immediately allows us to access its components, so it’s a nice way to parse the url, e.g.:
let url = new URL('https://javascript.info/url');
alert(url.protocol); // https:
alert(url.host); // javascript.info
alert(url.pathname); // /url
Here’s the cheatsheet for URL components:
hrefis the full url, same asurl.toString()protocolends with the colon character:search– a string of parameters, starts with the question mark?hashstarts with the hash character#- there may be also
userandpasswordproperties if HTTP authentication is present:http://login:password@site.com(not painted above, rarely used).
URL objects to networking (and most other) methods instead of a stringWe can use a URL object in fetch or XMLHttpRequest, almost everywhere where a URL-string is expected.
Generally, the URL object can be passed to any method instead of a string, as most methods will perform the string conversion, that turns a URL object into a string with full URL.
SearchParams “?…”
Let’s say we want to create a url with given search params, for instance, https://google.com/search?query=JavaScript.