Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegExp exec - string manipulation

I have a string that I am trying to manipulate using a regular expression as follows:

var str = 'This is a string with 1: {{param1}}, 2: {{param2}} and 3: {{param3}}',
    reg = /{{.*?}}/ig;

while (field = reg.exec(str)) {
    str = str.replace(field, 'test');
}

{{param2}} never gets replaced though - my guess is because I am manipulating the string while running it through RegExp.exec(...). But cannot be certain.

I have tried the following (as I noticed RegExp.exec(...) returns an array) - still no luck:

var str = 'This is a string with 1: {{param1}}, 2: {{param2}} and 3: {{param3}}',
    reg = /{{.*?}}/ig;

while (field = reg.exec(str)) {
    str = str.replace(field[0], 'test');
}

Any ideas?

Edit: current result of this function is:

'This is a string with 1: test, 2: {{param2}}, test and 3: test'
like image 514
keldar Avatar asked Sep 28 '22 01:09

keldar


1 Answers

You should 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 string with 1: test, 2: {{param2}} and 3: {{param3}}

Second :

This is a string with 1: test, 2: test and 3: {{param3}}

third :

This is a string with 1: test, 2: test and 3: test

Another option is to do :

 str = str.replace(/{{.*?}}/g, 'test');

This will also yield :

This is a string with 1: test, 2: test and 3: test

Edit :

To add to Anonymous's answer :

The problem is that each replace - makes the original string shorter.The indexes were calculated at the beginning with the original longer line .

In other words , had you wanted to replace to a same length expression as {{param1}} (which it's length is 9) , to another string with same length of 9 , say : **test1** , then your code would have worked :

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**

like image 108
Royi Namir Avatar answered Nov 15 '22 03:11

Royi Namir