Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex for replacing {{}} with {{{}}} conditionaly

In a large String, some words wrap by {{ }} in three ways:

 1. {{some words}}
 2. {{#some words}}
 3. {{/some words}}

I need a regex that just converts {{some words}} to {{{some words}}}. Is there any solution?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If I understand correctly you want to exclude some {{ }} patterns from adding these extra braces.

You can use [^#/] to match any character that is not # and / and use that in the overal regular expression:

let text = "{{hello}} {{#hello}} {{/hello}} {{world}} {{#world}} {{/world}}";
let result = text.replace(/\{\{[^#/].*?}}/g, "{$&}");
console.log(result);
  • .*? matches any character (except newline) in a lazy manner, i.e. it will stop matching when }} is encountered.
  • $& represents the complete matched string
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading