JavaScript location.host vs location.hostname
In this article, we will learn about how to get information related to the webpage like hostname, port number, etc. We will also see the difference between the location.hostname and location.host.
location object is used to get information about the current web page. host and hostname are properties of location objects.
location.hostname: This property will return the domain name of the web page.
Syntax:
location.hostname
Return value: It returns a string representing the domain name or IP address.
Example:
-
If this is our URL,
https://www.geeksforgeeks.org:8080/ds/heap
-
When we call location.hostname, This will return.
www.geeksforgeeks.org
HTML
<!DOCTYPE html> < html lang = "en" > < head > <!-- using jquery library --> < script src = </ script > </ head > < body > < script > document.write("hostname : " + location.hostname); </ script > </ body > </ html > |
Output:
In order to verify this thing for any webpage, open the webpage you want, then click on inspect and then write console.log(location.hostname) in the console tab. You will get the domain name of the webpage.
location.host: This property also returns the same hostname but it also includes the port number. In case, if the port number is not available, then it will just return the hostname.
Syntax:
location.host
Return value: It returns a string representing the domain name and port number.
Example:
-
If this is our URL,
https://www.geeksforgeeks.org:8080/ds/heap
-
When we call location.host, This will return.
www.geeksforgeeks.org:8080
HTML
<!DOCTYPE html> < html lang = "en" > < head > <!-- using jquery library --> < script src = </ script > </ head > < body > < script > document.write("host : " + location.host); </ script > </ body > </ html > |
Output:
location.hostname | location.host |
---|---|
It is a property of a location object. | It is also a property of a location object. |
It returns the domain name of the current webpage. | It returns the domain name as well as the port number (if available) of the current webpage. |
The return value is of String type. | The return value is of String type. |
Ex: www.abc.com | Ex: www.abc.com:8080 |
Please Login to comment...