Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!

How to match the exact string and replace all with other string using regular expression?

New member
Joined
Feb 2, 2023
Messages
7
Recently I came across one issue where I need to change the double curly braces with triple curly braces ,
The below example could clarify the need further,
let mystring = '{{Hello Tom}} , {{How are you doing today}}'

I need to change the above string and replace "{{" and "}}" with "{{{" and "}}}" respectively.
Currently I am using regex as below,
let output_string = mystring.replace(/{{/g, "{{{").replace(/}}/g, "}}}")

At the first execution its working fine and I got the desired output as '{{{Hello Tom}}} , {{{How are you doing today}}}' , when the next execution happen , it changed to 4 curly braces like below,
Output after second execution,
'{{{{Hello Tom}}}} , {{{{How are you doing today}}}}'

Its keep on increasing the curly braces whenever event is repeated.
I just want to replace 2 curly braces with 3,not any further
How can I Achieve this ???
 
New member
Joined
Feb 3, 2023
Messages
5
You can do it like this:

Code:
const output = input.replace(/\{+(.*?)\}+/g, (match, p1) => {
  return `{{{${p1}}}}`;
});
The regular expression pattern /\{+(.*?)\}+/g matches any number of curly braces, including none, and captures the text inside the braces in group 1.

Demo



Code:
const input = '{{Hello Tom}} , {{How are you doing today}}';

const input2 = '{{{Hello Tom}}} , {{{How are you doing today}}}';

const input3 = '{{{{Hello Tom}}}} , {{{{How are you doing today}}}}';

const output = input.replace(/\{+(.*?)\}+/g, (match, p1) => {
  return `{{{${p1}}}}`;
});

const output2 = input2.replace(/\{+(.*?)\}+/g, (match, p1) => {
  return `{{{${p1}}}}`;
});

const output3 = input3.replace(/\{+(.*?)\}+/g, (match, p1) => {
  return `{{{${p1}}}}`;
});

console.log(output)
console.log(output2)
console.log(output3)
 
Top