Find and Replace with JavaScript

I am trying to create a super simple template for JavaScript. I want to use the JavaScript method replaceto find all instances of curly braces in a template and replace them with the corresponding data.

For example, if my template was: <p>My name is {{name}}. I am {{age}}.</p>

I need the result: <p>My name is Olly. I am 19.</p>

Here is my code: http://jsfiddle.net/2RkAG/

I'm trying to automatically replace every piece of data, so I don’t need to explicitly tell JavaScript what to replace. However, this is where I have problems.

+5
source share
1 answer

$1 , . , , person["$1"] , .replace - person["$1"] undefined.

: http://jsfiddle.net/2RkAG/1/. , , , $1.

$result.html(template.replace(/{{(.*?)}}/g, function(a, b) {
    return person[b]; // a = complete match, b = first group
}));

{.

+4

All Articles