javascript - match string against the array of regular expressions

JavascriptArraysExpression

Javascript Problem Overview


Is there a way in JavaScript to get Boolean value for a match of the string against the array of regular expressions?

The example would be (where the 'if' statement is representing what I'm trying to achieve):

var thisExpressions = [ '/something/', '/something_else/', '/and_something_else/'];
var thisString = 'else';

if (matchInArray(thisString, thisExpressions)) {

} 

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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)​

Solution 3 - Javascript

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 */ }

Solution 4 - Javascript

look this way...

function matchInArray(stringSearch, arrayExpressions){
	var position = String(arrayExpressions).search(stringSearch);
    var result = (position > -1) ? true : false
    return result;
}

Solution 5 - Javascript

You can join all regular expressions into single one. This way the string is scanned only once. Even with a sligthly more complex regular expression.

var thisExpressions = [ /something/, /something_else/, /and_something_else/];
var thisString = 'else';


function matchInArray(str, expr) {
    var fullExpr = new RegExp(expr
        .map(x=>x.source) // Just if you need to provide RegExp instances instead of strings or ...
        // .map(x=>x.substring(1, x.length -2)  // ...if you need to provide strings enclosed by "/" like in original question.
        .join("|")
    )
    return str.match(fullExpr);

};


if (matchInArray(thisString, thisExpressions)) {
    console.log ("Match!!");
} 

In fact, even with this approach, if you need check the same expression set against multiple strings, this is a few suboptimal because you are building (and compiling) the same regular expression each time the function is called.

Better approach would be to use a function builder like this:

var thisExpressions = [ /something/, /something_else/, /and_something_else/];
var thisString = 'else';

function matchInArray_builder(expr) {
    var fullExpr = new RegExp(expr
        .map(x=>x.source) // Just if you need to provide RegExp instances instead of strings or ...
        // .map(x=>x.substring(1, x.length -2)  // ...if you need to provide strings enclosed by "/" like in original question.
        .join("|")
    )   
    
    return function (str) {
        return str.match(fullExpr);
        
    };
};  

var matchInArray = matchInArray_builder(thisExpressions);

if (matchInArray(thisString)) {
    console.log ("Match!!");
} 

Solution 6 - Javascript

Consider breaking this problem up into two pieces:

  1. filter out the items that match the given regular expression
  2. determine if that filtered list has 0 matches in it
const sampleStringData = ["frog", "pig", "tiger"];

const matches = sampleStringData.filter((animal) => /any.regex.here/.test(animal));

if (matches.length === 0) {
  console.log("No matches");
}

Solution 7 - Javascript

let expressions = [ '/something/', '/something_else/', '/and_something_else/'];

let str = 'else';

here will be the check for following expressions:

if( expressions.find(expression => expression.includes(str) ) ) {

}

using Array .find() method to traverse array and .include to check substring

Solution 8 - Javascript

Andersh's solution will not work if you have global flags.
A true return will toggle on and off on future identical tests.

regexArray.some(rx => rx.test("a"));    //true
regexArray.some(rx => rx.test("a"));    //false
regexArray.some(rx => rx.test("a"));    //true

(read why here)

This works and is also a one-liner:

const regexList = [/apple/, /pear/];
const string = "banana pear";
const isMatch = regexList.map(rx=>rx.source).includes(string);

.source returns the text of the RegExp pattern.
The arrow function returns an array of the source of every element. They will now be strings.
.includes returns if the string is in the array (if you need the index, use .indexOf)

Alternatively:

function isInsideArray(string, regexArray){
    return(regexArray.map(regex=>regex.source).includes(string)); 
}

Solution 9 - Javascript

If you would like to use String.match(), in case your array contains both match strings and regular expressions, you can do

let str = "The quick brown fox";
let matches = ["fox", "The.*fox", /the.*fox/i];
let strInMatches = matches.some(match => str.match(match));
console.log(strInMatches);

Solution 10 - Javascript

So we make a function that takes in a literal string, and the array we want to look through. it returns a new array with the matches found. We create a new regexp object inside this function and then execute a String.search on each element element in the array. If found, it pushes the string into a new array and returns.

// literal_string: a regex search, like /thisword/ig
// target_arr: the array you want to search /thisword/ig for.

function arr_grep(literal_string, target_arr) {
  var match_bin = [];
  // o_regex: a new regex object.
  var o_regex = new RegExp(literal_string);
  for (var i = 0; i < target_arr.length; i++) {
    //loop through array. regex search each element.
    var test = String(target_arr[i]).search(o_regex);
    if (test > -1) {
    // if found push the element@index into our matchbin.
    match_bin.push(target_arr[i]);
    }
  }
  return match_bin;
}

// arr_grep(/.*this_word.*/ig, someArray)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser398341View Question on Stackoverflow
Solution 1 - JavascriptandershView Answer on Stackoverflow
Solution 2 - JavascriptGillesCView Answer on Stackoverflow
Solution 3 - JavascriptLikwid_TView Answer on Stackoverflow
Solution 4 - JavascriptDaniel ArenasView Answer on Stackoverflow
Solution 5 - JavascriptbitifetView Answer on Stackoverflow
Solution 6 - Javascriptuser1429980View Answer on Stackoverflow
Solution 7 - JavascriptMubeen KhanView Answer on Stackoverflow
Solution 8 - JavascriptAndrei ClelandView Answer on Stackoverflow
Solution 9 - JavascriptaljgomView Answer on Stackoverflow
Solution 10 - JavascriptModView Answer on Stackoverflow