How to search for a string inside an array of strings

前端 未结 4 1475
梦如初夏
梦如初夏 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 04:49

    It's faster to avoid using regular expressions, if you're just trying to find the first substring match within an array of string values. You can add your own array searching function:

    Code:

    Array.prototype.findFirstSubstring = function(s) {
                for(var i = 0; i < this.length;i++)
                {
                    if(this[i].indexOf(s) !== -1)
                        return i;
                }
                return -1;
            };
    

    Usage:

    i.findFirstSubstring('height');
    

    Returns:

    -1 if not found or the array index of the first substring occurrence if it is found (in your case would be 2)

    0 讨论(0)
  • 2020-11-27 04:56

    You can use Array.prototype.find function in javascript. Array find MDN.

    So to find string in array of string, the code becomes very simple. Plus as browser implementation, it will provide good performance.

    Ex.

    var strs = ['abc', 'def', 'ghi', 'jkl', 'mno'];
    var value = 'abc';
    strs.find(
        function(str) {
            return str == value;
        }
    );
    

    or using lambda expression it will become much shorter

    var strs = ['abc', 'def', 'ghi', 'jkl', 'mno'];
    var value = 'abc';
    strs.find((str) => str === value);
    
    0 讨论(0)
  • 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([ '<param name=\"bgcolor\" value=\"#FFFFFF\" />', '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;
    }
    
    0 讨论(0)
  • 2020-11-27 05:10

    It's as simple as iterating the array and looking for the regexp

    function searchStringInArray (str, strArray) {
        for (var j=0; j<strArray.length; j++) {
            if (strArray[j].match(str)) return j;
        }
        return -1;
    }
    

    Edit - make str as an argument to function.

    0 讨论(0)
提交回复
热议问题