Mayday Mayday - 3 months ago 7
Javascript Question

How to capture n groups in regex so i can substitute them in js

I have following string:


[{par1}, {par2}, ..., {parN}]


And I am capturing this with following regex:

(\{\S*\})


This works fine, and captures in groups my params: $1 = par1, $2 = par2... etc

My question is, I want to do some operation in javascript with all those groups.
I know how to do it for 1 group.

str.replace(new RegExp((\{\S*\}),g),'whatever'+$1) //Probably need to add more escape characters


My question is how to replace $1 to 'whatever+'$1, $2 to 'whatever'+$2... etc

i.e


[{par1},{par2}] ==> [mypar1,mypar2]


EDIT

To explain what i want to do more detailed with parameters:

From [{par1},{par2}] I need to extract par1 and par2, so i can call a function with them, which will return different values:

function translate(par) {
//return different things for every parameter
}
//so finally will be like:
str.replace(new RegExp((\{\S*\}),g),translate($1))

Answer

Use callback function as a second argument of String.replace function:

var str = '[{par1}, {par2}, ..., {parN}]',
    prefix = 'whatever',
    replaced = str.replace(/\{(\S+)\}/g, function (p0, p1) {
        // ... some other logic
        return prefix + p1;
    });

console.log(replaced);  // "[whateverpar1, whateverpar2, ..., whateverparN]"
Comments