#AD Top Online Web Development & Programming Courses | Udemy
Newsletter Screenshot

How to get the domain name from a URL in JavaScript

Last modified June 11th 2024 | GitHub Source Code [GitHub] | #js

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 a 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 complete 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.comCode 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.comCode 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&worldCode language: JavaScript (javascript)

The URL API is currently supported by all modern browsers with a polyfill available for IE.

That’s all for this tutorial hopefully you found it helpful. While you’re here be sure checkout our other practical Javascript tutorials and consider signing up to our email newsletter to get updates when new tutorials are published.

Related Posts

#AD Shop Web Developer T-Shirts