RegExp.exec does not return global results

According to the MDC https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp/exec the following code should register each of the global matches for this regular expression.

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 ends. Any ideas why.

+1
source share
2 answers

Only one match, since overlapping is not allowed. Match:

 (^|\\+) - ^ (1\\+1) - 1+1 ($|\\+) - + 

It should be clear that there can be no other match, since at least 1+1 is required for each match, and only one is left 1. As a separate note, using the regular expression literal is simpler:

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

Your regular expression will not match this line more than once, since matches cannot match. Do you have another sample string that you are trying to match, or more detailed information about what you need from the string?

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

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

Source: https://habr.com/ru/post/1395653/


All Articles