簡體   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