简体   繁体   中英

How to search for a string inside an array elements using javascript?

var objTittleArr= ["Game of Thrones", "Suits", "Breaking Bad", "Legend of Korra"];

How can i find array items includes a string?

I tried to find array items includes 'orr' as below. where am I going wrong? How can i find them?

for (var j=0; j<objTittleArr.length; j++) {

        if (objTittleArr[j].match(/orr/g))
        {
             alert(objTittleArr[j]);
       }
        j++;
    }

Remove the j++; after the if , it makes the loop increment twice each iteration, so you're skipping odd-indexed elements.

Also, just in case - Legend of Korra needs to be between quotes.

Or you can keep in an array the matched element like:

var res = objTittleArr.filter(x => x.indexOf("orr") !== -1)
console.log(res); //[ 'Legend of Korra' ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM