6

Can I check whether the port number is existing in a given URL string or not?

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

Out of all the above options, if the port number is existing, then do nothing otherwise append 8080 by default with an end slash 8080/.

Is it possible in JavaScript?

10 Answers 10

9

You can try to use the location object and use:

location.port

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

5

Here you go the easiest way, set the href attribute.

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"

read more here

4

You can use location.port property.

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

Try below code

urlSplit = url.split(":")
if(urlSplit.length==3){
    port  = urlSplit[2];
}
else{
   port  = 80;
}
1
  • Please note, that when using https protocol, default port is 443, not 80.
    – Kejml
    Commented May 30, 2016 at 8:56
1

You can check Location

Location.port will serve your purpose

1

See if this works for you:

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

If you want to do that on user entered location:

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

:)

1
  • Change ":8080" to ":8080/" as it's requested on question.
    – KuKeC
    Commented May 30, 2016 at 7:08
1

use location.port. Sample example below.

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

Use this:

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

You can use Location Object of js

location.port
1

Just use location in debugger you will get host hostname href origin pathname port protocol and many more values

Not the answer you're looking for? Browse other questions tagged or ask your own question.