2

Please see below example and correct me if I am doing it wrong,

let _regex = new RegExp("L", "gi");
var strings = ["List", "List Items", "List attachments"];
for (let i = 0; i < strings.length; i++) {
  if (_regex.test(strings[i])) {
    console.log(strings[i]);
  }
}

Expected result is : all 3 results But logs only two List and List attachments

zb'
  • 8,071
  • 4
  • 41
  • 68
jithu reddy
  • 849
  • 1
  • 10
  • 19

1 Answers1

4

Regular expressions are mutable objects. The test method will mutate the lastIndex property, when that happens the first index has already been checked, so the second item in the array won't check that index. Since nothing is found at that point the index resets back to zero, that's why the last item works too. You can reset the index at every step:

for (let i = 0; i < strings.length; i++) {
  _regex.lastIndex = 0; // reset index
  if (_regex.test(strings[i])) {
    console.log(strings[i]);
  }
}

Or just use a regex literal:

for (let i = 0; i < strings.length; i++) {
  if (/L/gi.test(strings[i])) {
    console.log(strings[i]);
  }
}
elclanrs
  • 92,861
  • 21
  • 134
  • 171