JavaScript 匹配数组 [英] 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) {
例如:
string = "the word tree is in this sentence";
array[0] = "dog";
array[1] = "cat";
array[2] = "bird";
array[3] = "birds can fly";
在上面的例子中,条件为假.
但是,string = "她告诉我鸟可以飞,我同意"
会返回 true.
In the above example, the condition would be false.
However, string = "She told me birds can fly and I agreed"
would return true.
推荐答案
如何在需要时动态创建正则表达式(假设数组随时间变化)
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');
}
演示:
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()
方法
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');
}
演示:
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 匹配数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!