Search code examples
javascriptregexregex-group

How can I capture all groups and replace them with the reformatted version of the group?


TEXT IN:

some "single , quote" , text ""{one,2two space,three-dash,four}"" "{some,text}"  ""{alpha,bravo space - dash,charlie}"" some text

TEXT OUT:

some "single , quote" , text ""{one","2two space","three-dash","four}"" "{some,text}"  ""{alpha","bravo space - dash","charlie}"" some text

I have a javascript solution below that works, but i'm wondering if there is a better solution?

const str = "some \"single , quote\" , text \"\"\{one,2two space,three-dash,four\}\"\" \"\{some,text\}\"  \"\"\{alpha,bravo space - dash,charlie\}\"\" some text"
let res = str;
const matches = res.match(/""{([^"])*}""/g);
matches?.forEach( match => {
   res = res.replace(match, match.replace(/,/g,'","'));
});
console.log(str); // TEXT IN
console.log(res); // TEXT OUT

Solution

  • You can give a function as the replacement argument to the replace() method, so you don't need the loop.

    Also, your regexp can be simplified. You don't need the capture group, just put the * quantifier after [^"]

    const str = 'some, text ""{one,2two space,three-dash,four}"" some, text ""{alpha,bravo space - dash,charlie}"" some text';
    
    res = str.replace(/""{[^"]*}""/g, match => match.replace(/,/g, '","'))
    console.log(res);