JavaScript 匹配数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6219960/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript match against array
提问by Xi Vix
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.
在上面的例子中,条件为假。
但是,string = "She told me birds can fly and I agreed"
会返回true。
回答by Gabriele Petrioli
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');
}
demohttp://jsfiddle.net/gaby/eM6jU/
演示http://jsfiddle.net/gaby/eM6jU/
For browsers that support javascript version 1.6 you can use the some()
method
对于支持 javascript 1.6 版的浏览器,您可以使用该some()
方法
if ( array.some(function(item){return (new RegExp('\b'+item+'\b')).test(string);}) ) {
alert('match');
}
回答by Ville
(Many years later)
(多年以后)
My version of @Gaby's answer, as I needed a way to check CORS origin against regular expressions in an array:
我的@Gaby 答案版本,因为我需要一种方法来根据数组中的正则表达式检查 CORS 来源:
var corsWhitelist = [/^(?:.+\.)?domain\.com/, /^(?:.+\.)?otherdomain\.com/];
var corsCheck = function(origin, callback) {
if (corsWhitelist.some(function(item) {
return (new RegExp(item).test(origin));
})) {
callback(null, true);
}
else {
callback(null, false);
}
}
corsCheck('otherdomain.com', function(err, result) {
console.log('CORS match for otherdomain.com: ' + result);
});
corsCheck('forbiddendomain.com', function(err, result) {
console.log('CORS match for forbiddendomain.com: ' + result);
});
回答by T1000
Is that ok ?
这可以吗 ?
function checkForMatch(string,array){
var arrKeys = array.length;
var match = false;
var patt;
for(i=0; i < arrKeys; i++ ){
patt=new RegExp(" "+array[i]+" ");
if(patt.test(string))
match = true;
}
return match;
}
string = "She told me birds can fly and I agreed";
var array = new Array();
array[0] = "dog";
array[1] = "cat";
array[2] = "bird";
array[3] = "birds can fly";
alert(checkForMatch(string, array));
回答by Mike Samuel
If you have the literal strings in an array called strings
you want to match, you can combine them into an alternation by doing
如果您strings
想要匹配的数组中有文字字符串,您可以通过执行以下操作将它们组合成一个交替
new RegExp(strings.map(
function (x) { // Escape special characters like '|' and '$'.
return x.replace(/[^a-zA-Z]/g, "\$&");
}).join("|"))
If 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
如果您不只有文字字符串,并且想要组合正则表达式,那么您可以使用http://code.google.com/p/google-code-prettify/source/browse/trunk/js-modules/combinePrefixPatterns。 js
/**
* Given a group of {@link RegExp}s, returns a {@code RegExp} that globally
* matches the union of the sets of strings matched by the input RegExp.
* Since it matches globally, if the input strings have a start-of-input
* anchor (/^.../), it is ignored for the purposes of unioning.
* @param {Array.<RegExp>} regexs non multiline, non-global regexs.
* @return {RegExp} a global regex.
*/