针对JavaScript的数组比赛 [英] javascript match against array

查看:143
本文介绍了针对JavaScript的数组比赛的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好计算器:结果
我想知道如何匹配常规的前pressions数组的字符串。结果
我知道如何做到这一点通过数组循环。结果
我也知道如何通过相隔很长的定期EX pression做到这一点|结果
我希望像

Hello StackOverflow:
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";  

在上面的例子中,条件将是假的。结果,
然而,字符串=她告诉我,鸟能飞,我同意了将返回true。结果
先谢谢了。

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

推荐答案

如何在飞行中创建常规的前pression当你需要它(的假设随着时间的推移阵列变化

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

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

有关支持JavaScript 1.6版本,你可以使用<一个浏览器href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some\"><$c$c>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');
}

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

这篇关于针对JavaScript的数组比赛的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆