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');
});
}
}
}
2 Answers 2
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.
If you intend to do regular expression matching, start with regular expressions, not strings.
var arr = [/test/, /foo/, /bar/, /news-\d+/];
Then you can do normal matching without weird string rewrites or intepretations:
var matched = arr.some(re => re.test(...))
if (matched) {
doSomeThing()
}
or
for (re of arr) {
if (re.test(...)) {
doSomeThing();
break;
}
}
callback(). Just posting my code waitvar arr = [/test/, /foo/, /bar/, /news-\d+/];and then do anarr.forEach(re => re.test(...))orfor (re of arr) { re.test(...) }(with the benefit that the latter will let you break out of the loop, while the former won't)