如何使用jQuery从URL获取端口号?

the*_*van 0 javascript url port jquery

这是URL:

http:// localhost:8888/index.html. 
Run Code Online (Sandbox Code Playgroud)

如何使用jQuery从此URL获取端口号?

Fab*_*tté 9

它在location对象中可用:

location.port
Run Code Online (Sandbox Code Playgroud)

请注意,当URL中没有端口时,location.port将返回一个空字符串.

如果您需要在使用隐式默认端口时获取端口,请尝试:

var port = location.port || (location.protocol === 'https:' ? '443' : '80');
Run Code Online (Sandbox Code Playgroud)

这应该足以满足通过http和https协议提供的页面.