Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript match against array

I would like to know how to match a string against an array of regular expressions.
I know how to do this looping through the array.
I also know how to do this by making a long regular expression separated by |
I was hoping for a more efficient way like

if (string contains one of the values in array) {

For example:

string = "the word tree is in this sentence";  
array[0] = "dog";  
array[1] = "cat";  
array[2] = "bird";  
array[3] = "birds can fly";  

In the above example, the condition would be false.
However, string = "She told me birds can fly and I agreed" would return true.

like image 344
Xi Vix Avatar asked Jun 02 '11 20:06

Xi Vix


2 Answers

How about creating a regular expression on the fly when you need it (assuming the array changes over time)

if( (new RegExp( '\\b' + array.join('\\b|\\b') + '\\b') ).test(string) ) {
  alert('match');
}

demo:

string = "the word tree is in this sentence"; 
var array = [];
array[0] = "dog";  
array[1] = "cat";  
array[2] = "bird";  
array[3] = "birds can fly";  

if( (new RegExp( '\\b' + array.join('\\b|\\b') + '\\b') ).test(string) ){
    alert('match');
}
else{
    alert('no match');
}

For browsers that support javascript version 1.6 you can use the some() method

if ( array.some(function(item){return (new RegExp('\\b'+item+'\\b')).test(string);}) ) {
 alert('match');
}

demo:

string = "the word tree is in this sentence"; 
var array = [];
array[0] = "dog";  
array[1] = "tree";  
array[2] = "bird";  
array[3] = "birds can fly";  

if ( array.some(function(i){return (new RegExp('\\b'+i+'\\b')).test(string);}) ) {
 alert('match');
}
like image 175
Gabriele Petrioli Avatar answered Oct 11 '22 01:10

Gabriele Petrioli


(Many years later)

My version of @Gaby's answer, as I needed a way to check CORS origin against regular expressions in an array:

var corsWhitelist = [/^(?:.+\.)?domain\.com/, /^(?:.+\.)?otherdomain\.com/];

var corsCheck = function(origin, callback) {
  if (corsWhitelist.some(function(item) {
    return (new RegExp(item).test(origin));
  })) {
    callback(null, true);
  } 
  else {
    callback(null, false);
  }
}

corsCheck('otherdomain.com', function(err, result) {
  console.log('CORS match for otherdomain.com: ' + result);  
});

corsCheck('forbiddendomain.com', function(err, result) {
  console.log('CORS match for forbiddendomain.com: ' + result);  
});
like image 24
Ville Avatar answered Oct 11 '22 01:10

Ville