According to MDC https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp/exec the following code should log each of the global matches for this regexp.
var str = "(^|\\+)(1\\+1)($|\\+)";
var regex = new RegExp(str, "g");
var result;
var testString = "1+1+1";
while ((result = regex.exec(testString)) != null)
{
console.log(result);
}
But all I get is the first match and then the loop finishes. Any ideas why.
There’s only one match, since overlapping is not allowed. The match is:
It should be clear there can’t be another match, since every match requires at least
1+1, and there’s only a single 1 left. As a separate note, using a regex literal is simpler: