In this post, we will learn how to get domain name from URL in JavaScript. By the way, there are many different ways to extract a domain name from a URL. We learn about all those methods here. Then you are free to use the method that you find easy.

How To Get The Domain Name From URL in JavaScript ?

Get The Domain Name From URL 

Different methods to get domain name from URL are as follows:

The replace() method

With the replace() method, removes http, https and www and then separates the domain name before (.) with the help of split() method.

var url = "";

var domain = url.replace('http://','').replace('https://','').replace('www.','').split(".")[0];

console.log(domain); //output: codexradar code-box


The URL Web API is an easy way to get a domain name from a URL. With this help, we can get the domain name from the URL very easily.

For this, we will follow the following steps:

  • First let's create an object with the help of new URL() constructor.
  • Now with the help of this object we can get the domain name easily.
  • With the help of the repalce() method to get a completely naked domain, we remove www.
  • To remove .com we use split() method.
  • With the help of this created object, we can also get some extra property of the domain like pathname, protocol and search.

var url = "";

var domain = new URL(url);

domain = domain.hostname;

console.log(domain); //output:

// To remove www. we use replace() method

domain = domain.hostname.replace('www.','');

console.log(domain); //output:

// To remove .com we use split() method

domain = domain.hostname.replace('www.','').split(".")[0];

console.log(domain); //output: codexradar

// Get some extra property of the domain

var pathname = domain.pathname;

console.log(pathname); //output: search

var protocol = domain.protocol;

console.log(protocol); //output: https

var search =;

console.log(search); //output: ?q=html code-box

The window.location Object

To extract the URL of the current page, we use the window.location object of javascript.

var domain = window.location.hostname;

console.log(domain); //output:

domain = domian.replace('www.','').split(".")[0];

console.log(domian); //output: codexradar code-box

Thus, by using all these methods, we can easily get the domain name from the URL.


In this post we learn how to get the domain name form URL in JavaScript. You try to make it yourself. I hope you make. If you face any problem, then comment and tell us. Keep visiting the blog to read more similar posts.

Post a Comment

Previous Post Next Post