[英]how to check port number in url string?
Can I check whether the port number is existing in a given URL string or not? 我可以检查端口号是否存在于给定的URL字符串中?
Like sometimes a user can type 202.567.89.254:8088
or http://202.567.89.254:8088/
or http://202.567.89.254
. 有时,用户可以键入202.567.89.254:8088
或http://202.567.89.254:8088/
或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/
. 在以上所有选项中,如果端口号存在,则默认情况下不执行任何操作,默认情况下使用结束斜杠8080/
附加8080
。
Is it possible in JavaScript? 在JavaScript中可以吗?
Here you go the easiest way, set the href
attribute. 在这里,您可以使用最简单的方法,设置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"
You can use location.port property. 您可以使用location.port属性。
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;
}
use location.port
. 使用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
和更多值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.