How to search for a string inside an array of strings

前端 未结 4 1523
梦如初夏
梦如初夏 2020-11-27 04:06

After searching for an answer in other posts, I felt I have to ask this. I looked at How do I check if an array includes an object in JavaScript? and Best way to find if an

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 05:02

    Extending the contains function you linked to:

    containsRegex(a, regex){
      for(var i = 0; i < a.length; i++) {
        if(a[i].search(regex) > -1){
          return i;
        }
      }
      return -1;
    }
    

    Then you call the function with an array of strings and a regex, in your case to look for height:

    containsRegex([ '', 'sdafkdf' ], /height/)
    

    You could additionally also return the index where height was found:

    containsRegex(a, regex){
      for(var i = 0; i < a.length; i++) {
        int pos = a[i].search(regex);
        if(pos > -1){
          return [i, pos];
        }
      }
      return null;
    }
    

提交回复
热议问题