JavaScript与数组匹配

Xi *_*Vix 10 javascript arrays match

我想知道如何将字符串与正则表达式数组匹配.
我知道如何在数组中循环.
我也知道如何通过用|分隔长的正则表达式来做到这一点
我希望有一种更有效的方式

if (string contains one of the values in array) {
Run Code Online (Sandbox Code Playgroud)

例如:

string = "the word tree is in this sentence";  
array[0] = "dog";  
array[1] = "cat";  
array[2] = "bird";  
array[3] = "birds can fly";  
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,条件将为false.
但是,string = "She told me birds can fly and I agreed"会返回true.

Gab*_*oli 21

如何在需要时动态创建正则表达式(假设数组随时间变化)

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

演示 http://jsfiddle.net/gaby/eM6jU/


对于支持javascript版本1.6的浏览器,您可以使用该some()方法

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

http://jsfiddle.net/gaby/eM6jU/1/


Vil*_*lle 5

(许多年后)

我的@Gaby的答案版本,因为我需要一种方法来检查数组中正则表达式的CORS原点:

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);  
});
Run Code Online (Sandbox Code Playgroud)