0

I am trying to solve some JS problem. I want to check if an IP address is a valid one. So the numbers must be between 0-255.

So what I want to do at this point, is to get an IP ex 192.168.1.1 and get substrings and load them to an array, so I want to create an array that looks like that:

array = ['192' , '168' , '1' , '1'];

I've tried various approaches in my algorithm but can't manage to target dynamically the numbers and split them between every dot.

I've done several tries, and thats the closest I could get.

let str = '192.168.1.1';

isValidIp(str);

function isValidIP(str) {
let array = [];
let substringArray = [];
for (let i=0; i<str.length; i++){

if (str[i] == '.') array.push(i);

}

let counter = 0;
for (let i in array){
substringArray.push(str.substring(counter, array[i]));
counter = array[i];
}
console.log(substringArray);
}


Which returns:

[ '192', '.168', '.1' ]
TheoKondak
  • 9
  • 1
  • 5
  • Related [javascript regular expression to check for IP addresses](https://stackoverflow.com/q/4460586/1715579) and [Regular expression for IP Address Validation](https://stackoverflow.com/q/10006459/1715579) – p.s.w.g May 15 '19 at 19:08

4 Answers4

1

You can use the split() function of JavaScript which returns an array of every element separated by the digit specified. Or, which I wouldn't recommend, you could use RegEx. Here is an example of both:

function isValidIPwRegEx(str){
 if (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(str))
  {
    return true;
  }
return false;
}

function isValidIP(str) {
    let array = str.split("."),
        isIP = true;
    array = array.filter( block => !block.includes("+") && !block.includes("e") );
    if(array.length!=4) return false;
    array.forEach((number) => {
        if ( !(+number >=0 && +number <= 255) ) { //As @p.s.w.g kindly suggested
            isIP = false;
        }
    });
    return isIP;
}

//With RegEx
console.log("With RegEx");
console.log(isValidIPwRegEx("192.168.1.1"));
console.log(isValidIPwRegEx("blah.blah.blah.blah")); //As @georg suggested
console.log(isValidIPwRegEx("1e1.2e1.+3e1.+5e1")); //As @georg again suggested to @Nina Scholz
console.log("");
//Without RegEx
console.log("Without RegEx");
console.log(isValidIP("192.168.1.1"));
console.log(isValidIP("blah.blah.blah.blah")); //As @georg suggested
console.log(isValidIP("1e1.2e1.+3e1.+5e1")); //As @georg again suggested to @Nina Scholz
console.log(isValidIP("1e1.2e1.3e1.5e1"));
k3llydev
  • 2,057
  • 2
  • 11
  • 21
  • How about `isValidIP("blah.blah.blah.blah")`? – georg May 15 '19 at 19:26
  • 1
    Regarding @georg's comment, `"blah.blah.blah.blah"` passes because `+'blah' < 0` → `NaN < 0` → `false` so it skips the `isIP = false` check. You can fix this by simply inverting the conditions, i.e. `if (!(+number >=0 && +number <= 255))` (I know this seems like the same logic, but it's subtly different because `!(NaN >= 0)` → `true`) – p.s.w.g May 15 '19 at 19:39
  • @georg I edited and now it handles correctly your comment. And you are right @p.s.w.g, what do you think it's more efficient? `isNaN(number)` as a condition? Or your example of changing the logic of the if statement? – k3llydev May 15 '19 at 19:46
  • @k3llydev: thanks for fixing, but see also my comment to the Nina's answer ;) Hint: casting to Number won't work here at all, you need regular expressions, because dotted quad IP are _strings_ and should be treated as such. – georg May 15 '19 at 19:47
  • @georg Thanks for your time, do you think any of my two solutions would work like that? – k3llydev May 15 '19 at 20:01
  • @p.s.w.g I used your condition, I thought it would be the simplest.. Thank you.. Do you think my answer is more accurate now? – k3llydev May 15 '19 at 20:04
  • Thank you for your explicit reply @k3llydev. I will study it and see your algorithm and syntax. Split seems to be that I was looking for. Other than that, my homework has a couple more restrictions, which I didn't include to the question since I am trying to cope with it on my own in order to get into algorithmic thinking. – TheoKondak May 16 '19 at 12:33
  • @TheKondak if you think I already gave you the help you needed, please feel free to upvote and accept the answer. Otherwise, you can edit your question and be as specific as you can to cover all the restrictions you have to solve this. If so, please leave a comment here so I get notified when you edited and I'll help you for sure. – k3llydev May 16 '19 at 12:43
0

Use String's split function.

So, something like "192.168.1.1".split(".")

LA Imagine
  • 29
  • 4
  • Thanks for your reply. Unfortunately, due to my low reputation, I can't upvote you yet. This method seems to be what I was looking for. – TheoKondak May 15 '19 at 19:20
0

You could split the string and check if the length is four and all values are integers and smaller than 256.

var ip = '192.168.1.1',
    values = ip.split('.'),
    valid = values.length === 4 && values.every(v => +v >= 0 && +v < 256);

console.log(values);
console.log(valid);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0
function isValidIP(str) {
    let re = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
    let m = str.match(re);
    return m &&
           m[1] >= 0 && m[1] <= 255 &&
           m[2] >= 0 && m[2] <= 255 &&
           m[3] >= 0 && m[3] <= 255 &&
           m[4] >= 0 && m[4] <= 255
           ;
}

If you wish to be more precise, each digit check can be:

(0|[1-9]\d{0:2})

This prevents extraneous leading 0's.

Booboo
  • 38,656
  • 3
  • 37
  • 60