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)
}
0

3 Answers 3

4

var arr = ["OTHER-REQUEST-ASFA","OTHER-REQUEST-ASFB","OTHER-REQUEST-ASFC"]
var a = arr.filter(s => s.includes("ASFB"));
console.log(a);

3
  • I got a syntax error with this solution.
    – BobbyJones
    Commented Dec 21, 2017 at 17:53
  • What is your actual code then? It works in the snippet above. If it's giving you a syntax error it's definitely something that differs between your code and mine. Copy/paste my code and it'll work.
    – ctwheels
    Commented Dec 21, 2017 at 17:55
  • c'est manifique Commented Aug 24, 2022 at 14:22
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');
  }

});

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)

1
  • I got a syntax error with this solution.
    – BobbyJones
    Commented Dec 21, 2017 at 17:53

Not the answer you're looking for? Browse other questions tagged or ask your own question.