简体   繁体   中英

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.

Here is what I did to extract the ip, but failed!

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

window.location.hostname and window.location.port

Read more about window.location at 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;

FIDDLE

If it's coming from the adressbar, this is already built in to document.location

This is a simple method to parse the information from a given URL-string (not necessarily from the actual 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM