![](/img/trans.png)
[英]How can I sign the current port to my URL if I have a string with the port number in the url link
[英]how to check port number in url string?
我可以檢查端口號是否存在於給定的URL字符串中?
有時,用戶可以鍵入202.567.89.254:8088
或http://202.567.89.254:8088/
或http://202.567.89.254
。
在以上所有選項中,如果端口號存在,則默認情況下不執行任何操作,默認情況下使用結束斜杠8080/
附加8080
。
在JavaScript中可以嗎?
在這里,您可以使用最簡單的方法,設置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.