JavaScript article thumbnail image.

In a web page URL, the hostname (i.e. "") is either the registered name or IP address assigned to a web page or website (can include a port number as well).

When programming in JavaScript, how do you get the URL hostname and port number of the current page?

JavaScript has a built-in way to get this information 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 method looks like in practice:

This will return a string value containing the hostname and, if the port value is non-empty, a : symbol along with the port number of the URL.

Here are some example returned values to expect:

// Page URL: = ""

// Page URL: = ""

// Page URL: http://localhost:3000 = "localhost:3000"

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

Thanks for reading and happy coding!

About the author

Hi, I'm Nick Major. I'm a software developer from Wisconsin, United States.

I create free and premium courses, have published hundreds of informational coding articles, and am currently a Frontend Software Engineer at RoundingWell.

You can read more about me here.

Picture of Nick Major.