How to get the hostname from a URL in JavaScript?
18 April 2020
When dealing with URLs in JavaScript, we often need to get the host value or root URL. So, how can you get the hostname from a URL in JavaScript?
This is very easily achieved using the Web API’s URL Interface.
const testUrl = new URL("http://testing.com");This creates an object like so:

We can then access the hostname property:
console.log(testUrl);
// testing.comThis is a great modern way to create a URL object from a string URL and gives a whole host of other properties to access.
Supporting older browsers
If you are constrained by not having the ability to use modern browser we can use an alternative:
var parser = document.createElement('a');
parser.href = "http://testing.com";
parser.host;
// testing.comThis is an interesting little work around. Basically, we are creating an anchor element and assigning our URL to its href value. This essentially exposes the host property on the DOM interface.