Skip to content Skip to sidebar Skip to footer

Regexp.exec Not Returning Global Results

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

Solution 1:

There's only one match, since overlapping is not allowed. The match is:

(^|\\+) - ^

(1\\+1) - 1+1

($|\\+) - +

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:

var regex = /(^|\+)(1\+1)($|\+)/g;

Solution 2:

Your regular expression won't match that string more than once since the matches can't overlap. Do you have another sample string you're trying to match, or more details on what you need from the string?

Regardless, I would use a RegExp object literal instead; less escaping and you can specify the global flag directly.

var regex = /(^|\+)(1\+1)($|\+)/g;

Post a Comment for "Regexp.exec Not Returning Global Results"