As I work on parsing template files in my code, one of my first tasks involves removing all Mustache variables in the template. The majority of these variables follow this structure:
{{variable}}, {{#loop}}{{content}}{{/loop}}, {{^not}}{{/not}}, {{! comment }}, {{#if}}{{/if}}
Up until now, I've been using the following regex replace method to successfully eliminate these variables:
markup.replace(/\{\{[^\}\}]*\}\}/g, "")
However, I recently encountered an issue where I discovered a Mustache comment that encloses some javascript code.
{{! App.doStuff('magic_string')({flag:true, flag2: true}); }}
- Please note: The .js code within the comment does NOT include
}}
.
Initially, I believed that my regex would search for {{
until it reached }}
(exactly 2 in a row) ([^\}\}]
), but this is not the case. The matching process halts as soon as it encounters a single }
, resulting in the failure to remove this comment from the template file since it couldn't identify the opening and closing {{ }}
pair.
Query: How can I modify my regex to ensure it captures from '{{' to '}}' without pausing at a single '}'?
Sample scenarios:
"<p>{{! App.doStuff('magic_string')({flag:true, flag2: true}); }}</p>".replace(/\{\{[^\}\}]*\}\}/g, "");
"<p>{{! App.doStuff('magic_string')({flag:true, flag2: true}); }}</p>"
// incorrect - should be "<p></p>"
"<p>{{test}}</p>".replace(/\{\{[^\}\}]*\}\}/g, "");
"<p></p>" // correct
"<p>{{#test}}{{.}}{{/test}}</p>".replace(/\{\{[^\}\}]*\}\}/g, "");
"<p></p>" // correct
"<p>{{>partial}}</p>".replace(/\{\{[^\}\}]*\}\}/g, "");
"<p></p>" // correct
"<p {{#flag}}class='fancy'{{/flag}}></p>".replace(/\{\{[^\}\}]*\}\}/g, "");
"<p class='fancy'></p>" // correct