You must remove the g flag.
var str = 'This is a string with 1: {{param1}}, 2: {{param2}} and 3: {{param3}}', reg = /{{.*?}}/; while (field = reg.exec(str)) { str = str.replace(field, 'test'); console.log(str) }
Result:
First iteration:
This is a line with 1: test, 2: {{param2}} and 3: {{param3}}
The second:
This is the line with test 1: test, 2: test and 3: {{param3}}
third:
This is the line with test 1: test, 2: test and 3: test
Another variant:
str = str.replace(/{{.*?}}/g, 'test');
This will also give:
This is the line with test 1: test, 2: test and 3: test
Edit:
To add an anonymous answer:
The problem is that each replace makes the original line shorter. Indexes were calculated at the beginning with the original longer string.
In other words, if you wanted to replace an expression of the same length as {{param1}} (whose length is 9) with another line with the same length of 9, say: **test1** , then your code would work:
var str = 'This is a string with 1: {{param1}}, 2: {{param2}} and 3: {{param3}}', reg = /{{.*?}}/g while (field = reg.exec(str)) { str = str.replace(field, '**test1**'); console.log(str) }
Result:
This is a string with 1: **test1**, 2: **test1** and 3: **test1**