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