0

i have written bellow code in javascript

function reg()
{
    var a="ec2-54-234-174-228.compute-1.amazonaws.com";
    var r = a.match(/\-[0-9]*/g);
    alert(r);
}

i got output like -54,-234,-174,-228,-1 but i need to extract only 54-234-174-228 IP address from variable a.

4
  • match returns an array, always Commented Sep 3, 2013 at 9:35
  • Try alert(r[0] + '-' + r[1] + '-' + r[2] + '-' + r[3]). Commented Sep 3, 2013 at 9:36
  • 1
    The hostname-extraction does not work if the hostname naming strategy is changed at some later time by amazon and if it then does not anymore include the IP address's numbers. E.g. it could be hello-xaby.compute-1.amazonaws.com in the future. Do not try to extract the IP with string operations from the hostname. Instead, do a DNS lookup. Commented Sep 3, 2013 at 9:38
  • my output is wrong because it also include -1 that is unnecessary for me. please can anyone write code for that? Commented Sep 3, 2013 at 9:40

7 Answers 7

2

Try this:

function reg()
{
    var a="ec2-54-234-174-228.compute-1.amazonaws.com";
    var r = a.match(/\-[0-9-]*/g);
    alert(r[0].substring(1,r[0].length));
}

a.match(/\-[0-9-]*/g); will return [-54-234-174-228,-1]. Getting the first element and removing - from the beginning you get what your IP. You can also add this:

alert(r[0].substring(1,r[0].length).replace(/-/g, '.'));

to return it in IP shape: 54.234.174.228

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

1 Comment

Don't forget IP addresses are reversed in reverse-records. In this case the IP associated with the reverse-record would be 228.174.234.54
2

Try this regexp: /[0-9]{1,3}(-[0-9]{1,3}){3}(?=\.)/

It matches a series of 4 numbers between 1 and 3 digits separated by -, which must be followed by a dot.

Comments

1

get the index of first "." then slice

function reg()
{
    var a="ec2-54-234-174-228.compute-1.amazonaws.com";
    var r = a.indexOf(".");
    alert(a.slice(0,r));
}

1 Comment

Within the alert, change it to Array.prototype.slice.call(a.slice(0,r).split('-'), 1).join('-')
1
"ec2-54-234-174-228.compute-1.amazonaws.com".split('.')[0].split('-').slice(1,5).join('.')

Comments

0

In your case you can simply use this pattern:

var r = a.match(/([^a-z][0-9]+\-[0-9]+\-[0-9]+\-[0-9]+)/g);

Comments

0

One more example:

function reg() {
    var a="ec2-54-234-174-228.compute-1.amazonaws.com";
    var re = /-(\d+)/ig
    var arr = [];
    while(digit = re.exec(a)) arr.push(digit[1]);
    arr = arr.slice(0,4);

    alert(arr)
}

Comments

0

you can use this regEx

"(\\d{2}-\\d{3}-\\d{3}-\\d{3})+"

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.