In this tutorial I’ll show you how to get the domain name from a URL using JavaScript.
Please note if you require the domain name from the current page being viewed you can simply use window.location.hostname
. This tutorial is for those that want to extract the domain from a URL provided in a data source.
First let’s create a string with our URL:
const url = "https://www.example.com/blog?search=hello&world";
Code language: JavaScript (javascript)
Next we create a URL object using the new URL()
constructor:
let domain = (new URL(url));
Code language: JavaScript (javascript)
This constructor is part of the browser URL API. It allows us to create a URL object from a string similar to the object created using window.location
. With the object created we can access the hostname
property which returns a string containing the domain name:
domain = domain.hostname;
console.log(domain); //www.example.com
Code language: JavaScript (javascript)
If you require a naked domain the www
can be removed using the replace()
method.
domain = domain.hostname.replace('www.','');
console.log(domain); //example.com
Code language: JavaScript (javascript)
The URL API is currently supported by all modern browsers with a polyfill available for IE.