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:
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:
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:
If you require a naked domain the
www can be removed using the
Some additional properties you can access using the URL constructor include:
The URL API is currently supported by all modern browsers with a polyfill available for IE.