-2

Someone can explain to me while this piece of code doesn't find all the occurrences?

var re = /000/g;
var str = "000000"
while ((match = re.exec(str)) != null) {
    console.log("match found at " + match.index);
}

it prints

match found at 0
match found at 3

but it's not true. Matches should be at indexes 0, 1, 2, 3!

Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476
Canemacchina
  • 119
  • 10

1 Answers1

0

You need a positive lookahead which does not consume the found length of the searching pattern.

var re = /0(?=00)/g;
var str = "000000"
while ((match = re.exec(str)) != null) {
    console.log("match found at " + match.index);
}
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358