The URL API in JavaScript

The URL API parses data from an URL and makes them accessible through utility properties. The URL() constructor creates and returns a new URL object from the URL string.

const url = new URL('https://myshop.com/mobiles?brand=samsung');

Properties

Let’s check out some of the most used properties.

host

This property returns the domain of the URL followed by the port (if it exists).

// URL without any port
let url = new URL('https://myshop.com/mobiles?brand=samsung');
console.log(url.host); // myshop.com

// URL without any port
url = new URL('https://myshop.com:8080/mobiles?brand=samsung');
console.log(url.host); // myshop.com:8080

hostname

This property also returns the domain of the URL but without the port.

const url = new URL('https://myshop.com:8080/mobiles?brand=samsung');
console.log(url.hostname); // myshop.com

port

This property returns the port of the URL.

const url = new URL('https://myshop.com:8080/mobiles?brand=samsung');
console.log(url.port); // 8080

origin

This property returns the domain along with the scheme and port of the URL.

const url = new URL('https://myshop.com:8080/mobiles?brand=samsung');
console.log(url.origin); // https://myshop.com:8080

pathname

This property returns the path of the URL excluding the query string.

const url = new URL('https://myshop.com/mobiles?brand=samsung');
console.log(url.pathname); // /mobiles

search

This property returns the query string of the URL.

const url = new URL('https://myshop.com/mobiles?brand=samsung&color=black');
console.log(url.search); // ?brand=samsung&color=black

searchParams

This property returns a URLSearchParams object that we can use to parse data from the query string of the URL.

const url = new URL('https://myshop.com/mobiles?brand=samsung&color=black');
const search = url.searchParams;
console.log(search.get('brand')); // samsung
console.log(search.get('color')); // black
console.log(search.has('color')); // true
console.log(search.has('size')); // false

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *