-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
  • 607,720
  • 39
  • 448
  • 563
Canemacchina
  • 159
  • 13

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
  • 376,160
  • 25
  • 347
  • 392