简体   繁体   中英

javascript array | return an index if value contains a string

I have an array of strings stringsArr and also I have a string myString . I would like to find first index of my array for which value is euqal myString OR contains myString .

I know method indexOf(), but unfortunatelly it works only if value equals myString . I googled through documentation, but didn't find anything suitable, so decided to ask here if I didn't miss something.

You want to use findIndex and a custom predicate like:

stringsArr.findIndex(function (str) {
  return (str === myString || str.indexOf(myString) > -1);
});

If you're using an environment(/browser) that doesn't provide findIndex , the MDN page includes a nice short polyfill.

indexOf is probably what you want, but using indexOf on the String:

var tested = ['foot','bark', 'foo','cat'];
var match = 'foo';
for(var i = 0; i < tested.length; i++)
    if(tested[i].indexOf(match) > -1) console.log(i);

That will output 0 and 2.

To get the actual index:

var tested = ['foot','bark', 'foo','cat'];
var match = 'foo';
var index = -1;
for(var i = 0; i < tested.length; i++) {
    if(tested[i].indexOf(match) > -1) {
       index = i;
       break;
    }
} 

console.log(index); // 0, as "foot" includes "foo".

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