javascript - match string against the array of regular expressions

前端 未结 8 1515
予麋鹿
予麋鹿 2020-12-02 22:23

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\' statemen

8条回答
  •  离开以前
    2020-12-02 22:48

    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)
    

提交回复
热议问题