繁体   English   中英

如何检查url字符串中的端口号?

[英]how to check port number in url string?

我可以检查端口号是否存在于给定的URL字符串中?

有时,用户可以键入202.567.89.254:8088http://202.567.89.254:8088/http://202.567.89.254

在以上所有选项中,如果端口号存在,则默认情况下不执行任何操作,默认情况下使用结束斜杠8080/附加8080

在JavaScript中可以吗?

您可以尝试使用location对象并使用:

location.port

HTMLHyperlinkElementUtils.port属性是一个USVString,包含URL的端口号。

在这里,您可以使用最简单的方法,设置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"

在这里阅读更多

您可以使用location.port属性。

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

看看这是否适合您:

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
}

:)

试试下面的代码

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

你可以查看位置

Location.port将满足您的需求

使用location.port 以下示例示例。

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

用这个:

  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和更多值

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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