In this tutorial I’ll show you how to get the domain name from a URL using JavaScript. Many tutorials around the web use complicated regular expression to achieve this task but it can be done in a more straight forward way using the URL API.
Note – if you are looking to get the domain name from the current page being viewed in a browser you can simply use window.location.hostname
. This tutorial is for those that need to extract the domain name from a URL that’s part of 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)
If this isn’t a correctly formatted full URL e.g example.com/blog
an error is thrown.
Next create a URL object using the new URL()
constructor:
let domain = (new URL(url));
Code language: JavaScript (javascript)
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 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)
Some additional properties you can access using the URL constructor include:
const pathname = domain.pathname;
console.log(pathname); // blog
const protocol = domain.protocol;
console.log(protocol); // https
const search = domain.search;
console.log(search); // ?search=hello&world
Code language: JavaScript (javascript)
The URL API is currently supported by all modern browsers with a polyfill available for IE. Hopefully you found this tutorial helpful, if so you might enjoy some of these other practical Javascript tutorials.