DEV Community

Michael Burrows
Michael Burrows

Posted on • Updated on • Originally published at michaelburrows.xyz

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

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';
Enter fullscreen mode Exit fullscreen mode

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

let domain = (new URL(url));
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.','');
Enter fullscreen mode Exit fullscreen mode

Top comments (0)