简体   繁体   中英

how to check port number in url string?

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?

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.

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

You can use location.port property.

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

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
}

:)

Try below code

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

You can check Location

Location.port will serve your purpose

use location.port . Sample example below.

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

Use this:

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

您可以使用js的Location Object

location.port

只需在调试器中使用location ,您将获得host hostname href origin pathname port protocol和更多值

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM