Working with URL in JavaScript
In JavaScript, sometimes you have to work
with links addresses. The URL class
is designed for this, allowing you to get
and change parts of addresses.
Let's see how to work with it on the following address example:
let path = 'http://site.ru:3000/dir/eee/page.html#show?a=1&b=2&c=3';
Let's create an object of the URL
class, passing our address as a parameter:
let url = new URL(path);
Let's see what properties the created object has.
Protocol
Using the protocol property,
you can get the protocol type:
let res = url.protocol;
console.log(res); // shows 'http://'
Host
Using the host property, you
can get a domain name with a port:
let res = url.host;
console.log(res); // shows 'site.ru:3000'
Host name
Using the hostname property, you
can get the domain name:
let res = url.hostname;
console.log(res); // shows 'site.ru'
Port
Using the port property,
you can get a port:
let res = url.port;
console.log(res); // shows '3000'
Path
Using the pathname property, you
can discard a domain name and get a path:
let res = url.pathname;
console.log(res); // shows '/dir/eee/page.html#show?a=1&b=2&c=3'
Hash
Using the hash property, you
can get the hash value:
let res = url.hash;
console.log(res); // shows 'show'
GET parameters
Using the search property, you
can get a string with GET parameters:
let res = url.search;
console.log(res); // shows 'a=1&b=2&c=3'
Using the searchParams property,
you can get GET parameters as an object
of the
URLSearchParams class:
let res = url.searchParams;
console.log(res); // outputs an object of the URLSearchParams class