</> Michael Burrows

Get the domain name from a string containing a URL in JavaScript

Last modified on September 27th 2020 GitHub [Source] CodePen [Demo]

Parsing URL’s is a common task when developing web applications. Fortunately JavaScript’s URL API makes it easy to read and modify URL’s without the need for REGEX.

First let’s create a string with our URL (Note: If the URL isn’t correctly structured you’ll get an error).

const url = 'https://www.michaelburrows.xyz/blog?search=hello&world';

Next we create a URL object using the new URL() constructor.

let domain = (new URL(url));

With the object created there are a number of properties we can access.

We’re interested in the hostname property which returns a string containing the domain name.

domain = domain.hostname; console.log(domain); //www.michaelburrows.xyz

If you require a naked domain (without the www) it can be removed using the replace() method.

domain = domain.hostname.replace('www.',''); console.log(domain); //michaelburrows.xyz

Alternatively the code can be written as follows:

const url = 'https://www.michaelburrows.xyz/blog?search=hello&world'; const domain = (new URL(url)).hostname.replace('www.','');