In this article I will show how to get domain name from a given URL using JavaScript.
We will get domain name without REGEX, because JavaScript URL API makes it easy to read and modify URL without the need for REGEX.
First let’s create a string with our URL:
const url = "https://www.devs3.pro/profile/engrmahabub";
If this isn’t a correctly formatted complete URL e.g devs3.pro/profile/engrmahabub
an error is thrown.
Next we create a URL object using the new URL()
constructor.
let domain = (new URL(url));
The URL()
constructor allows us to create a URL object from a string similar to the object created when using window.location
.
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.devs3.pro
If you require a naked domain the www can be removed using the replace()
method.
domain = domain.hostname.replace('www.','');
console.log(domain); //devs3.pro
Alternatively the code can be written as follows:
const url = "https://www.devs3.pro/profile/engrmahabub";
const domain = (new URL(url)).hostname.replace('www.','');
Some additional properties you can access using the URL constructor include:
const pathname = domain.pathname;
console.log(pathname); // /profile/engrmahabub
const protocol = domain.protocol;
console.log(protocol); // https