0

Let's suppose I have HTML template file containing such string:

<p> >>LEFT PART<< {{Data}} >>RIGHT PART<< </p>

Let's suppose both left and right part of this string dont contain nothing like {{Data}}, and I want to implement a function which takes this file and object like {Data:"My nice data",Name:"Sebastian"} and returns file containing

<p> >>LEFT PART<< My nice data >>RIGHT PART<< </p>

instead. It's easy to do it by using string.prototype.replace actually. But now I have couple of questions:

  1. How do JS template engines perform similar tasks? In order to make my question certain and concrete lets say I'm talking about Jade, but you can describe another engine/framework like Pug, Dot etc.. Do they use Regular Expressions or some tricky algorithms searching for a substring?
  2. Will I lose perceptible execution speed if I use Regular Expressions and both left and right parts of my string contain ~10000 letters? Or html file contains 100+ lines of code.

P.S. I googled these questions, but most answers describe how to render page by using framework/engine, not how they do it.

  • Most likely, a templating engine would index all locations for `{{` and `}}` in a string, then apply some substring logic to get/validate the data between them and ensure every open token is followed by a closing token. You can also accomplish this with regex, but a proper regex to do this (using [tempered greedy token](https://stackoverflow.com/a/37343088/3600709)) `{{((?:(?!}}).)+)}}` (or `{{2}((?:(?!}{2}).)+)}{2}`) isn't very efficient on long strings - that's where the indexing would prevail. – ctwheels Nov 08 '19 at 17:02
  • Thank You! Cant upvote your comment but its useful – SpeciallyTrainedMacaque Nov 08 '19 at 17:39

1 Answers1

0

To answer your two questions, in order:

  1. Simpler JS templating libraries tend to search for the open-character(s) using a basic JS String#indexO call, just as you'd expect. But others — especially ones that don't build their own templating from scratch — often rely upon more complex techniques.

    Vue, as a counterexample, uses lodash.template in its templating engine, which heavily relies upon regexes under the hood.

  2. You don't want to do this with a regex, because regular expressions start traversing their state machine every time they begin a match; this is a lot of extra processing overhead on sufficiently large strings which is not required in the "indexOf" technique in #1. (For small templates, or sufficiently powerful machines, this isn't a huge time difference; but it's worth paying attention to on a big, or massively parallel, job!)

A final caveat: Many modern JS templating engines (Vue included) convert the template into a set of smaller strings before beginning the template string replacement; this enables them to benefit from the improved runtime (and parallelization) of processing shorter strings.

Community
  • 1
  • 1
j6m8
  • 2,261
  • 2
  • 26
  • 34