user1082754
user1082754

Reputation:

Find and replace with JavaScript

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.

Upvotes: 5

Views: 655

Answers (1)

pimvdb
pimvdb

Reputation: 154918

$1 only works if you pass a string directly. It does not work the way you have it, because person["$1"] is evaluated before the string is passed to .replace - and person["$1"] literally is undefined.

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.

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

You don't need to escape the first {, either.

Upvotes: 4

Related Questions