Is there a javascript method to find substring in an array of strings?

前端 未结 5 1216
醉话见心
醉话见心 2021-01-26 08:58

Suppose my array is [\"abcdefg\", \"hijklmnop\"] and I am looking at if \"mnop\" is part of this array. How can I do this using a javascript method?

I tried this and it

相关标签:
5条回答
  • 2021-01-26 09:32
    var array= ["abcdefg", "hijklmnop"];
    var newArray = array.filter(function(val) {
        return val.indexOf("mnop") !== -1
    })
    console.log(newArray)
    
    0 讨论(0)
  • 2021-01-26 09:33

    a possible solution is filtering the array through string.match

    var array= ["abcdefg", "hijklmnop"];
    
    var res = array.filter(x => x.match(/mnop/));
    
    console.log(res)

    0 讨论(0)
  • 2021-01-26 09:34

    You can use Array#some:

    // ES2016
    array.some(x => x.includes(testString));
    
    // ES5
    array.some(function (x) {
      return x.indexOf(testString) !== -1;
    });
    

    Note: arrow functions are part of ES6/ES2015; String#includes is part of ES2016.

    The Array#some method executes a function against each item in the array: if the function returns a truthy value for at least one item, then Array#some returns true.

    0 讨论(0)
  • 2021-01-26 09:35

    Can be done like this https://jsfiddle.net/uft4vaoc/4/

    Ultimately, you can do it a thousand different ways. Almost all answers above and below will work.

    <script>
    var n;
    var str;
    var array= ["abcdefg", "hijklmnop"];
    //console.log(array.indexOf("mnop")); //-1 since it does not find it in the string
    for (i = 0; i < array.length; i++) { 
        str = array[i];
        n = str.includes("mnop");
        if(n === true){alert("this string "+str+" conatians mnop");}
    }
    </script>
    
    0 讨论(0)
  • 2021-01-26 09:41

    Javascript does not provide what you're asking before because it's easily done with existing functions. You should iterate through each array element individually and call indexOf on each element:

    array.forEach(function(str){
        if(str.indexOf("mnop") !== -1) return str.indexOf("mnop");
    });
    
    0 讨论(0)
提交回复
热议问题