Select Objects in Array Based on Regex Match

前端 未结 2 740
粉色の甜心
粉色の甜心 2021-01-11 23:11

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

2条回答
  •  时光取名叫无心
    2021-01-11 23:54

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

提交回复
热议问题