Home >Web Front-end >JS Tutorial >How to get the hostname of the current URL in javascript?

How to get the hostname of the current URL in javascript?

青灯夜游
青灯夜游Original
2019-01-03 14:14:336826browse

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.

How to get the hostname of the current URL in javascript?

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:

How to get the hostname of the current URL in javascript?

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:

How to get the hostname of the current URL in javascript?

##Assume the current URL is: http: //127.0.0.1/demo/2.html, if the port is not specified in the URL, only the host name will be displayed, and there will be no port number

How to get the hostname of the current URL in javascript?

Browser support

The browsers that support the hostname attribute or host attribute of the location object are as follows:

1, Google Chrome

2, Apple Safari

3, Firefox

4, Opera

5, 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Related articles

See more