JavaScript 与数组匹配
我想知道如何将字符串与正则表达式数组进行匹配。
我知道如何循环遍历数组。
我也知道如何通过制作一个由 |
分隔的长正则表达式来做到这一点 我希望有一种更有效的方法
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。
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) {
For example:
string = "the word tree is in this sentence";
array[0] = "dog";
array[1] = "cat";
array[2] = "bird";
array[3] = "birds can fly";
In the above example, the condition would be false.
However, string = "She told me birds can fly and I agreed"
would return true.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如何在需要时动态创建正则表达式(假设数组随时间变化)
演示:
对于支持 javascript 版本 1.6 的浏览器,您可以使用
some( )
方法演示:
How about creating a regular expression on the fly when you need it (assuming the array changes over time)
demo:
For browsers that support javascript version 1.6 you can use the
some()
methoddemo:
(多年后)
我的@Gaby 答案版本,因为我需要一种方法来根据数组中的正则表达式检查 CORS 来源:
(Many years later)
My version of @Gaby's answer, as I needed a way to check CORS origin against regular expressions in an array:
可以吗?
Is that ok ?
如果您想要匹配名为
strings
的数组中的文字字符串,则可以通过执行以下操作将它们组合成一个替换:如果您不仅仅只有文字字符串,您想要组合正则表达式,那么您使用 http://code .google.com/p/google-code-prettify/source/browse/trunk/js-modules/combinePrefixPatterns.js
If you have the literal strings in an array called
strings
you want to match, you can combine them into an alternation by doingIf you don't have only literal strings, you want to combine regular expressions, then you use http://code.google.com/p/google-code-prettify/source/browse/trunk/js-modules/combinePrefixPatterns.js