Home >Web Front-end >JS Tutorial >How to get the hostname of the current URL in javascript?
In JavaScript, you can use the hostname attribute or host attribute of the location object to obtain the host name of the current URL. The following article will introduce you to these two attributes. I hope it will be helpful to you.
Use the location hostname attribute
The location hostname attribute is used to return the current URL Hostname; it returns a string containing the domain name or IP address of the URL.
Basic syntax:
location.hostname
Simple example:
Assume the current URL is: http:// www.php.cn/course/type/4.html
<script type="text/javascript"> var h = location.hostname; alert(h); </script>
Rendering:
Use location host attribute
location host attribute is used to set or return the host name and port of the URL; if the port is not specified in the current URL, the port number will not be returned.
Basic syntax:
location.host
Simple example:
Assume the current URL is: http://127.0.0.1 :8020/demo/2.html, the URL specifies the port number
<script type="text/javascript"> var h = location.host; alert(h); </script>
Rendering:
Browser support
The browsers that support the hostname attribute or host attribute of the location object are as follows: 1, Google Chrome2, Apple Safari3, Firefox4, Opera5, Internet Explorer The above is the entire content of this article, I hope it can be helpful to everyone Learning helps. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !The above is the detailed content of How to get the hostname of the current URL in javascript?. For more information, please follow other related articles on the PHP Chinese website!