0

I have some data that is like the following:

hello this is {{replacement_data}} and this {{replacement_data}} is {{replacement_data}}.

I want to use Mustache to replace these with an array of values:

[val1, val2, val3.

Is this type of thing possible? Currently, I'm writing an ugly loop in Java and looking to clean it up with something like this.

John Lippson
  • 839
  • 3
  • 10
  • 23
  • Possible duplicate of [Can mustache iterate a top-level array?](https://stackoverflow.com/questions/6516297/can-mustache-iterate-a-top-level-array) – F.Almeida Feb 19 '18 at 15:55
  • `hello this is {{replacement_data.0}} and this {{replacement_data.1}} is {{replacement_data.2}}` – Keith Feb 19 '18 at 15:59

1 Answers1

0

If this is as simple as it gets, you don't need handlebars or mustache. it is very simple to do with RegEx and a couple lines of code. See the example below. Given an array of replacements, in the same order as the content to be replaced, search for each and replace with corresponding array element.

Simple.

var replacements = ['first replacement', 'second replacement', 'third replacment'];

let subject = document.querySelector('div');
let input = subject.textContent;
let output = input.replace(/{{replace me}}/g, match=>replacements.shift());
subject.textContent = output;
<h3>Replacements below...</h3>
<div>
   This is some string with {{replace me}} and {{replace me}} and {{replace me}}!
</div>
Randy Casburn
  • 11,404
  • 1
  • 12
  • 26