Search code examples
regexnode.jsmustache

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.


Solution

  • 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.