Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I systematically replace text within mustache tags in a large body of text?

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.

like image 418
reedog117 Avatar asked Jun 25 '13 18:06

reedog117


2 Answers

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.

like image 159
Ethan Brown Avatar answered Sep 28 '22 10:09

Ethan Brown


Description

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

enter image description here

Javascript Code Example:

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}}
like image 41
Ro Yo Mi Avatar answered Sep 28 '22 09:09

Ro Yo Mi