I have quite a few templates that utilize mustache tags to determine where to place user data. These templates are stored as a string.
When I call the render function within mustache, I feed in a complex JSON object that contains a number of arrays of both strings and subdocuments.
I incorrectly declared within the mustache tag to use a particular element within array like so:
{{dataElementArray[2].subElement}}
{{anotherElement.dataArray[1]}}
Instead I would like to change all occurrences within each template to the proper mustache syntax for addressing elements like so:
{{dataElementArray.2.subElement}}
{{anotherElement.dataArray.1}}
What's the best way to systematically go through each template (represented as a string) and use regex's to change what is in each tag? I have over 50 templates, most of them hundreds of lines long with hundreds of tags within each one.
I am using JavaScript/Node.js for this app.
This is a tough (but not impossible) task to do with a single regular expression. Fortunately, there's no reason we have to do it with a single one. A much easier (and more robust) approach is to use two regular expressions: one to match replacement tags (things contained in {{curly brackets}}
) and another to replace instances of array indexers with dot indexers. Here's my solution:
s.replace( /\{\{(.*?)\}\}/g, function(x){ // this grabs replacement tags
return x.replace( /\[(\d+)\]/g,'.$1' )}); // this replaces array indexers
Note: I have not analyzed this solution with the entire mustache syntax, so I cannot guarantee it will work if you're using more than the standard tags.
This expression will match the first square bracketed numbers inside the mustache brackets, it also validates the square brackets are followed by either a dot or the close mustache bracket.
Use this regex: (\{\{[a-z.]*[a-z])\[(\d+)\](?=\.|\})([a-z.]*\}\})
With this replacement: $1.$2$3
http://www.myregextester.com/?r=f9e362af
Sample Input
{{dataElementArray[2].subElement}}
{{anotherElement.dataArray[1]}}
{{alreadyFormatted.dataArray.1}}
Code
<script type="text/javascript">
var re = /(\{\{[a-z.]*[a-z])\[(\d+)\](?=\.|\})([a-z.]*\}\})/;
var sourcestring = "source string to match with pattern";
var replacementpattern = "$1.$2$3";
var result = sourcestring.replace(re, replacementpattern);
alert("result = " + result);
</script>
After Replacement
{{dataElementArray.2.subElement}}
{{anotherElement.dataArray.1}}
{{alreadyFormatted.dataArray.1}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With