← coderrocketfuel.com

Get The URL Domain (Hostname) For A Web Page In JavaScript

In a web page URL, the hostname or domain (i.e. "example.com") is either the registered name or IP address given to a web page or website.

When you're coding in JavaScript, how do you get the URL hostname of a web page?

JavaScript has a built-in way to get this value using the Location API interface, which represents the location (URL) of the current web page you're located on. The global Window interface has access to the Location object that can be used via window.location.

Here's what the code looks like for retrieving the URL domain of a web page:


This will return a string value containing the domain (hostname) value for the URL.

Here are some example returned values to expect:

// Page URL: https://coderrocketfuel.com/courses
window.location.hostname = "coderrocketfuel.com"

// Page URL: https://www.coderrocketfuel.com/courses
window.location.hostname = "www.coderrocketfuel.com"

// Page URL: https://coderrocketfuel.com:80/courses
window.location.hostname = "coderrocketfuel.com"

// Page URL: https://subdomain.coderrocketfuel.com/courses
window.location.hostname = "subdomain.coderrocketfuel.com"

// Page URL: http://localhost:3000
window.location.hostname = "localhost"

For more information on the browser support for this method, see its MDN web docs page.

Thanks for reading and happy coding!