Javascript Location Port with Example
Javascript location port property sets or returns the port number of the current host. By default browser does not returns the port number by location.port property of the current host. If current URL is opened using the provided port number of the domain then you can retrieve it using location.port property into the Javascript code that can be used for different purposes in the code. You can also extract the location port using the location.host property that returns the hostname and port number. Javascript substring function can be applied on location.host property value retrieved, to get the port number.
JavaScript Window Location Object Examples:
You can see the live samples and examples of JavaScript Window Location Object from the following links:
Syntax for Javascript Location Port Property
location.port
or
window.location.port
Any of the above syntax can be used to retrieve the port number of the current Host.
Following syntax shows how to set the location.port property:
location.port = "value";
e.g.: location.port = "8080";
Example of Javascript Location Port Property
<script type="text/javascript" language="javascript">
function locationPort() {
alert(window.location.port);
// alternate method to get the port number
// using substring function on location.host property
var portNumber = new String();
portNumber = window.location.host;
portNumber = portNumber.substring(portNumber.indexOf(":") + 1);
alert(portNumber);
}
</script>
Above example will return the location.port value only if the URL contains the port number.
Output:
You can see the output of above discussed code from the following link:
Continue to next tutorial: Javascript Location Protocol with Example to learn how to get the protocol name of the current URL.
