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:

javascriptlet 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:

javascriptlet url = new URL(path);

Let's see what properties the created object has.

Protocol

Using the protocol property, you can get the protocol type:

javascriptlet res = url.protocol;
console.log(res); // shows 'http://'

Host

Using the host property, you can get a domain name with a port:

javascriptlet res = url.host;
console.log(res); // shows 'site.ru:3000'

Host name

Using the hostname property, you can get the domain name:

javascriptlet res = url.hostname;
console.log(res); // shows 'site.ru'

Port

Using the port property, you can get a port:

javascriptlet res = url.port;
console.log(res); // shows '3000'

Path

Using the pathname property, you can discard a domain name and get a path:

javascriptlet 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:

javascriptlet res = url.hash;
console.log(res); // shows 'show'

GET parameters

Using the search property, you can get a string with GET parameters:

javascriptlet 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:

javascriptlet res = url.searchParams;
console.log(res); // outputs an object of the URLSearchParams class