Get host, hostname, port in JavaScript of any webpage

In today’s article, we will learn about getting the host & the hostname of the webpage URL including/excluding the port number. The hostname is either the registered name (domain name) or IP address (server IP address) assigned to a website. In JavaScript it is quite easy to get this kind of information using the built-in functions of JS. To know the hostname of a website’s URL you can use window.location.hostname method. In which window.location function is used to access the current location of the webpage.

Examples & Code to Get Host, Hostname & Port


Example URL: http://localhost:3000

// HOST
Question: What is "Host" in the above URL?
Answer: "localhost:3000"
Syntax to get Host: window.location.host

// HOSTNAME
Question: What is "Hostname" in the above URL?
Answer: "localhost"
Syntax to get Hostname:  window.location.hostname

// PORT
Question: What is "Port" in the above URL?
Answer: "3000"
Syntax to get Port number: window.location.port
 

Compatibility

Chrome IE Edge Firefox Safari Opera
Yes Yes Yes Yes Yes Yes

For more information regarding the browser support for this host, hostname & port you can refer its MDN web doc’s page.

Leave a Comment