我可以检查端口号是否存在于给定的URL字符串中?
就像有时用户可以键入202.567.89.254:8088或http://202.567.89.254:8088/或http://202.567.89.254.
在上述所有选项中,如果端口号存在,则8080默认情况下不执行任何操作,并使用结束斜杠8080/.
在JavaScript中可以吗?
您可以尝试使用location对象并使用:
location.port
Run Code Online (Sandbox Code Playgroud)
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"
Run Code Online (Sandbox Code Playgroud)
阅读更多 在这里
看看这是否适合您:
function appendPort(url){
if(!url.match(/\:\d+$/)){
return url + ":8080";
}
}
Run Code Online (Sandbox Code Playgroud)
如果您想在用户输入的位置上执行此操作:
if(!location.port){
location.port = 8080; // doing this will take care of rest of the URL component
}
Run Code Online (Sandbox Code Playgroud)
:)
| 归档时间: |
|
| 查看次数: |
1763 次 |
| 最近记录: |