Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript check if an element content some part of an array

I have an array like this

var ALLOW_SUBNET = ['192.168.1.', '192.168.2.', '192.168.3.' , '192.168.4.'];

And I can get IP address of PC Client by using my own function:

getIPClient()
    var ipclient = input.getIPClient();

My question is how can I check if client IP is within my allowed subnet, I tried to use indexOf() function, but result was wrong. For example:

if IP Client is 192.168.1.115 => allow

if IP Client is 192.168.5.115 => deny.
like image 418
user3404580 Avatar asked Sep 01 '16 07:09

user3404580


2 Answers

You could use Array#some for it and check if a part of ALLOW_SUBNET is inside of ip at position 0.

function check(ip) {
    return ALLOW_SUBNET.some(function (a) { return !ip.indexOf(a); });
}

var ALLOW_SUBNET = ['192.168.1.', '192.168.2.', '192.168.3.', '192.168.4.'];

console.log(check('192.168.1.115'));
console.log(check('192.168.5.115'));

ES6 with String#startsWith

function check(ip) {
    return ALLOW_SUBNET.some(a => ip.startsWith(a));
}

var ALLOW_SUBNET = ['192.168.1.', '192.168.2.', '192.168.3.', '192.168.4.'];

console.log(check('192.168.1.115'));
console.log(check('192.168.5.115'));
like image 133
Nina Scholz Avatar answered Oct 01 '22 11:10

Nina Scholz


Here is a solution.

var ALLOW_SUBNET = ['192.168.1.', '192.168.2.', '192.168.3.', '192.168.4.'];

function checkIP(ip) {
  var allow = false;
  for (var i = 0; i <= ALLOW_SUBNET.length; i++) {
    if (ip.indexOf(ALLOW_SUBNET[i]) > -1) {
      allow = true;
      break;
    }
  }
  return allow;
}

console.log(checkIP('192.168.9.3'));

console.log(checkIP('192.168.1.3'));
like image 44
Pugazh Avatar answered Oct 01 '22 11:10

Pugazh