[英]Extract ip address and port from a string in javascript
In my client side code, the user enter an address like: 在我的客户端代码中,用户输入如下地址:
http://192.168.1.52:8080/home/client.html
I would like to extract the ip address 192.168.1.52 and the port number 8080 separately. 我想分别提取IP地址 192.168.1.52和端口号 8080。
Here is what I did to extract the ip, but failed! 这是我提取ip所做的,但失败了!
var url = window.location.href;
ValidIpAddressRegex = new RegExp("^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$");
var ip= ValidIpAddressRegex.exec(url);
alert(ip);
What would be the correct way of extracting IP and port number in javascript.- Thank you 在javascript中提取IP和端口号的正确方法是什么.-谢谢
window.location.hostname
and window.location.port
window.location.hostname
和window.location.port
Read more about window.location
at https://developer.mozilla.org/en-US/docs/Web/API/window.location 有关
window.location
更多信息, 请访问https://developer.mozilla.org/en-US/docs/Web/API/window.location
The easiest would be to just use a fake anchor : 最简单的方法是使用假锚:
var str = 'http://192.168.1.52:8080/home/client.html'
var a = document.createElement('a')
a.href = str;
var host = a.hostname;
var post = a.port;
If it's coming from the adressbar, this is already built in to document.location
如果它来自地址栏,则已经内置到
document.location
This is a simple method to parse the information from a given URL-string (not necessarily from the actual document.location) 这是一种从给定的URL字符串解析信息的简单方法(不一定是来自实际的document.location)
<script>
var url = 'http://192.168.1.52:8080/home/client.html';
var ip = url.split('/')[2].split(':')[0];
var port = url.split('/')[2].split(':')[1];
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.