Henry
Henry

Reputation: 1

Array comparison?

I am making a function that takes in an example and an ip address. For ex.

compare('192.168.*','192.168.0.42');  

The asterix indicates that the following parts of ip can be anything. The function returns true or false based on if the example and ip is a match. I tried this kind of solution.

var compare = function(example, ip){
  var ex = example.split(".");
  var ip = ip.split(".");
  var t = 0;
  for(var i=0; i<4; i++){
    if(ex[i] == ip[i] || ex[i] == "*" || typeof ex[i] === 'undefined' && ex[i-1] == "*"){
          t++
          if(t==4){
            return true
          }
       }else{
        return false;
      }
  }
}

What are the main advantages of using regular expression over this solution? What would be the best regular expression to do this?

Upvotes: 0

Views: 60

Answers (2)

Amberlamps
Amberlamps

Reputation: 40488

This goes way better with regular expressions. Try this:

function compare(example, ip) {
  var regexp = new RegExp('^' + example.replace(/\./g, '\\.').replace(/\*/g, '.*'));
  return regexp.test(ip);
}

compare('192.168.*', '192.168.0.42'); // => true
compare('192.167.*', '192.168.0.42'); // => false

What this does is, it translates your pattern to an regular expression. Regular expressions are extremely powerful in matching string. It also covers cases like this:

compare('192.168.*.42', '192.168.1.42'); // => true
compare('192.167.*.42', '192.168.1.43'); // => false

Upvotes: 0

void
void

Reputation: 36703

How about checking if they are not equal then just return false?

var compare = function(example, ip){

  // You should have some basic IP validations here for both example and ip.
  
  var ex = example.split(".");
  var ip = ip.split(".");
  for(var i=0; i<ex.length; i++){
    
      if(ex[i]=='*')
        break;
    
      if(ex[i]!=ip[i])
        return false;
  
  }
  
  return true;
}

alert(compare('333.321.*','333.321.345.765'));  
alert(compare('333.322.*','333.321.345.765'));  
alert(compare('333.321.345.*','333.321.345.765'));  

Upvotes: 1

Related Questions