0

Using the indexOf function, how can I get a positive result when searching an array for a wildcard card match such as the below? All I am currently getting is a negative result: (-1)

function test() {
    var arr = ["OTHER-REQUEST-ASFA","OTHER-REQUEST-ASFB","OTHER-REQUEST-ASFC"]
    var a = arr.indexOf("ASFB")
    alert(a)
}
takendarkk
  • 3,347
  • 8
  • 25
  • 37
BobbyJones
  • 1,331
  • 1
  • 26
  • 44

3 Answers3

4

var arr = ["OTHER-REQUEST-ASFA","OTHER-REQUEST-ASFB","OTHER-REQUEST-ASFC"]
var a = arr.filter(s => s.includes("ASFB"));
console.log(a);
ctwheels
  • 21,901
  • 9
  • 42
  • 77
1

var arr = ["OTHER-REQUEST-ASFA","OTHER-REQUEST-ASFB","OTHER-REQUEST-ASFC"]
var searchTerm = "ASFB";

arr.forEach(function(str, idx) {
  if (str.indexOf(searchTerm) !== -1 ){
    console.log(arr[idx] + ' contains "' + searchTerm  + '" at index ' + idx + ' of arr');
  }

});
Sébastien
  • 11,860
  • 11
  • 58
  • 78
0

You need to loop through the array and apply indexOf to each individual string, to get a single output, you can use Array.some, which returns true if any of the element in the array contains the substring:

var arr = ["OTHER-REQUEST-ASFA","OTHER-REQUEST-ASFB","OTHER-REQUEST-ASFC"]

var a = arr.some(s => s.indexOf("ASFB") !== -1)

console.log(a)
Psidom
  • 209,562
  • 33
  • 339
  • 356