How to check port number in url string?

Can I check if a port number exists in a given URL string or not?

How sometimes a user can type 202.567.89.254:8088or http://202.567.89.254:8088/or http://202.567.89.254.

Of all the above options, if the port number exists, then do nothing, otherwise add 8080a default with a slash 8080/.

Is this possible in JavaScript?

+4
source share
10 answers

You can try to use the location object and use:

location.port

The HTMLHyperlinkElementUtils.port property is a USVString containing the URL port number.

+8
source

You can use the location.port property.

  if(location.port){//then there is port}
  else{//No port}
+4

: href.

var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";


console.log(parser.protocol); // => "http:"
console.log(parser.hostname); // => "example.com"
console.log(parser.port);     // => "3000"
console.log(parser.pathname); // => "/pathname/"
console.log(parser.host);     // => "example.com:3000"

+3

, :

function appendPort(url){
    if(!url.match(/\:\d+$/)){
        return url + ":8080";
    }
}

:

if(!location.port){
    location.port = 8080; // doing this will take care of rest of the URL component
}

:)

+1
source

Try entering the code

urlSplit = url.split(":")
if(urlSplit.length==3){
    port  = urlSplit[2];
}
else{
   port  = 80;
}
+1
source

You can check Location

Location.port will serve your purpose

+1
source

use location.port. An example of an example is below.

function appendPort(){
  if(location.port.length === 0){
    location.host = location.host + ":8080/";
  }
}
+1
source

Use this:

  if(location.port){
    //then there is port
    //you may alert() if you want
  }
  else{
    location.port=8080;
  }
+1
source

You can use js location object

location.port
+1
source

Just use locationin the debugger, you will get host hostname href origin pathname port protocolmany more values

+1
source

All Articles