I am trying to create a super simple JavaScript templating solution. I want to use the JavaScript replace method to find all instances of curly braces in a template and replace them with their appropriate data.
For instance, if my template was: <p>My name is {{name}}. I am {{age}}.</p>
I would want the result: <p>My name is Olly. I am 19.</p>
Here’s my code so far: http://jsfiddle.net/2RkAG/
I’m trying to make it automatically replace each piece of data, so I don’t have to explicitly tell the JavaScript what to replace. However, this is where I am having problems.
$1only works if you pass a string directly. It does not work the way you have it, becauseperson["$1"]is evaluated before the string is passed to.replace– andperson["$1"]literally isundefined.You can pass a function instead: http://jsfiddle.net/2RkAG/1/. The function is called for each replacement and has arguments passed that are equivalent to e.g.
$1.You don’t need to escape the first
{, either.