How can I return only the objects in an array that meet a certain criteria using javascript?
For instance, if I have [\'apple\',\'avocado\',\'banana\',\'cherry\'] an
Your problem is with generating your regex on the fly. You cannot make a valid regex by concatenating strings. You have to use the constructor: RegExp() to make a regex from a string.
Here is my function for matching an array:
function matcharray(regexp, array) {
var filtered = [];
for (i = 0; i < array.length; i++) {
if (regexp.test(array[i])) {
filtered.push(array[i]);
}
}
return filtered;
}
You could call this function like so:
var myregex = "abc";
alert(matcharray(new RegExp(myregex), my_array).join());