When calling exec on a global regex, it remembers where was the last match and starts the next one from there.
var rx = /a/g, matches = rx.exec('aa');
rx.lastIndex; //1
When you modify your input string, between exec
calls, the lastIndex
becomes desychronised.
While there's a few way to fix this, I would rather perform the replace in a single statement.
'QUESTION1 + QUESTION2 + QUESTION3'.replace(/QUESTION\d+/g, function ($1) {
return 'VALUE_FOR_' + $1;
});
//"VALUE_FOR_QUESTION1 + VALUE_FOR_QUESTION2 + VALUE_FOR_QUESTION3"