How to loop all the elements that match the regex?
Solution 1:
var reg = /e(.*?)e/g;
var result;
while((result = reg.exec(targetText)) !== null) {
doSomethingWith(result);
}
Solution 2:
Three approaches depending on what you want to do with it:
-
Loop through each match:
.match
targetText.match(/e(.*?)e/g).forEach((element) => { // Do something with each element });
-
Loop through and replace each match on the fly:
.replace
const newTargetText = targetText.replace(/e(.*?)e/g, (match, $1) => { // Return the replacement leveraging the parameters. });
-
Loop through and do something on the fly:
.exec
const regex = /e(.*?)e/g; // Must be declared outside the while expression, // and must include the global "g" flag. let result; while(result = regex.exec(targetText)) { // Do something with result[0]. }
Solution 3:
Try using match() on the string instead of exec(), though you could loop with exec as well. Match should give you the all the matches at one go. I think you can omit the global specifier as well.
reg = new RegExp(/e(.*?)e/);
var matches = targetText.match(reg);
Solution 4:
targetText = "SomeT1extSomeT2extSomeT3extSomeT4extSomeT5extSomeT6ext"
reg = new RegExp(/e(.*?)e/g);
var result;
while (result = reg.exec(targetText))
{
...
}
Solution 5:
I kept getting infinite loops while following the advice above, for example:
var reg = /e(.*?)e/g;
var result;
while((result = reg.exec(targetText)) !== null) {
doSomethingWith(result);
}
The object that was assigned to result
each time was:
["", "", index: 50, input: "target text", groups: undefined]
So in my case I edited the above code to:
const reg = /e(.*?)e/g;
let result = reg.exec(targetText);
while(result[0] !== "") {
doSomethingWith(result);
result = reg.exec(targetText);
}