Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript if arrays contains string with regex

I want to found if the variable url matches to any value of the array
For example, here's my array:

var arr = ["test", "foo", "bar", "news-[0-999999999999999]*"];

... and my string

var url = "news-294";

I need to check for each arr value if it matches to url, with regex

So I've tried a foreach on the array, new RegExp for each value and then check if it matchs. But It didn't worked well, and It was leaking my browser memory (the CPU was at 24% for a blank page with the script)

How can I do that? Thanks

EDIT: here's my code:

var CMS = {
    RegexMatch: function(regex, str, callback) {
        while ((m = regex.exec(str)) !== null) {
            if(m[0] == str) callback();
        }
    },
    ArrayFindRegex: function(array, str, callback) {
        array.forEach(function(e) {
            CMS.RegexMatch(new RegExp(e), str, function() {
                callback();
            });
        });
    },
        Check: function() {
                var url = "blabla";
                CMS.ArrayFindRegex(["test", "foo", "bar", "news-[0-999999999999999]*"], url, function() {
                    console.log('wow');
                });
            }
        }
}

1 Answers

Try Array.prototype.filter instead. It's more idomatic than each (or other iteration methods, in this case). filter returns an array with the contents being any matches or empty if none are found.

var arr = ["test", "foo", "bar", "news-[0-999999999999999]*"];
var url = "news-294";

var matches = arr.filter(function(pattern) {
  return new RegExp(pattern).test(url);
})

console.log(matches);

The above example logs ["news-[0-999999999999999]*"]. You can assert a positive result based off the length of matches.

like image 145
Seth Avatar answered Sep 14 '25 21:09

Seth