javascript - match string against the array of regular expressions
look this way...
function matchInArray(stringSearch, arrayExpressions){
var position = String(arrayExpressions).search(stringSearch);
var result = (position > -1) ? true : false
return result;
}
Using a more functional approach, you can implement the match with a one-liner using an array function:
ECMAScript 6:
const regexList = [/apple/, /pear/];
const text = "banana pear";
const isMatch = regexList.some(rx => rx.test(text));
ECMAScript 5:
var regexList = [/apple/, /pear/];
var text = "banana pear";
var isMatch = regexList.some(function(rx) { return rx.test(text); });
http://jsfiddle.net/9nyhh/1/
var thisExpressions = [/something/, /something_else/, /and_something_else/];
var thisExpressions2 = [/else/, /something_else/, /and_something_else/];
var thisString = 'else';
function matchInArray(string, expressions) {
var len = expressions.length,
i = 0;
for (; i < len; i++) {
if (string.match(expressions[i])) {
return true;
}
}
return false;
};
setTimeout(function() {
console.log(matchInArray(thisString, thisExpressions));
console.log(matchInArray(thisString, thisExpressions2));
}, 200)
You could use .test() which returns a boolean value when is find what your looking for in another string:
var thisExpressions = [ '/something/', '/something_else/', '/and_something_else/'];
var thisString = new RegExp('\\b' + 'else' + '\\b', 'i');
var FoundIt = thisString.test(thisExpressions);
if (FoundIt) { /* DO STUFF */ }