How to systematically replace text in mustache tags in large text?

I have quite a few templates that use mustache tags to determine where to place user data. These templates are stored as a string.

When I call the render function in my mustache, I pass in a complex JSON object that contains several arrays of both strings and nested documents.

I incorrectly declared in the mustache tag to use a specific element in the array as follows:

{{dataElementArray[2].subElement}} {{anotherElement.dataArray[1]}} 

Instead, I would like to change all occurrences within each template to the correct mustache syntax to address such elements:

 {{dataElementArray.2.subElement}} {{anotherElement.dataArray.1}} 

What is the best way to systematically go through each pattern (represented as a string) and use a regular expression to change what each tag has? I have over 50 templates, most of which contain hundreds of lines with hundreds of tags in each of them.

I am using JavaScript / Node.js for this application.

+4
source share
2 answers

This is a difficult (but not impossible) task to do with one regular expression. Fortunately, there is no reason why we should do this with one. A much simpler (and more reliable) approach is to use two regular expressions: one to match replacement tags (things contained in {{curly brackets}} ), and the other to replace instances of array indexers with numeric indices. Here is 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 using the syntax of a whole mustache , so I can not guarantee that it will work if you use more than standard tags.

+5
source

Description

This expression will match the first square brackets in the mustache brackets, it also checks that the square brackets are accompanied by either a period or a parenthesis bracket.

Use this regular expression: (\{\{[az.]*[az])\[(\d+)\](?=\.|\})([az.]*\}\})

With this replacement: $1.$2$3

enter image description here

Javascript Code Example:

http://www.myregextester.com/?r=f9e362af

Input example

 {{dataElementArray[2].subElement}} {{anotherElement.dataArray[1]}} {{alreadyFormatted.dataArray.1}} 

code

 <script type="text/javascript"> var re = /(\{\{[az.]*[az])\[(\d+)\](?=\.|\})([az.]*\}\})/; 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}} 
+1
source

Source: https://habr.com/ru/post/1488142/


All Articles