JavaScript 匹配数组

标签 javascript arrays match

我想知道如何将字符串与正则表达式数组进行匹配。
我知道如何循环遍历数组。
我也知道如何通过制作一个由 |
分隔的长正则表达式来做到这一点 我希望有一种更有效的方式,比如

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

例如:

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

在上面的例子中,条件为假。
但是,string = "She told me birds can fly and I agreeed" 将返回 true。

最佳答案

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

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

演示:

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');
}


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

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

演示:

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');
}

关于JavaScript 匹配数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6219960/

相关文章:

java - 从 char 转换为 long

regex - 如何将正则表达式匹配到字符串末尾?

javascript - Sweet Alert JS库-修改动画速度

javascript - 是否可以将类 div 中的最后一个元素作为目标? CSS

javascript - 如何创建具有给定键和值的对象?

c++ - 数组值在 C++ 中自行改变

powershell - 如何选择数组属性匹配变量的对象?

collections - Neo4j/Cypher 中二维 COLLECTION 中的节点上的 MATCH

javascript - 通过数组转换在数组中按值查找键

javascript - 在nodejs中加密字符串的快速而安全的方法?