3

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

4 Answers 4

6

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

Sign up to request clarification or add additional context in comments.

Comments

5

window.location.hostname and window.location.port

Read more about window.location at https://developer.mozilla.org/en-US/docs/Web/API/window.location

1 Comment

Yes, this is it. I didn't realize he was actually getting the value from the window.location :-)
3

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>

Comments

1

if the string is a valid URL you can use this

const url = new URL('http://192.168.1.52:8080/home/client.html');
console.log(url.hostname) // 192.168.1.52
console.log(url.port) // 8080 

note that it'll throw in case the string is is not a valid URL

For the current page URL, as suggested before, use window.location object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.