How to search for a string inside an array of strings

前端 未结 4 1519
梦如初夏
梦如初夏 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)

提交回复
热议问题