How to get the hostname from a URL in JavaScript?

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.com

This 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.com

This 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.

Proudly published with Gatsby