I am coding a simple templating function in javascript.
I have my template loading fine, now is the part when I need to parse the content to the placeholders.
<var data = {
name: 'zerkms',
age: 42
};
var str = '{{name}} is {{age}}'.replace(/\{\{(.*?)\}\}/g, function(i, match) {
return data[match];
});
console.log(str);
http://jsfiddle.net/zDJLd/
Well, first you'll need the g
flag on the regex. This tells JavaScript to replace all matched values. Also you can supply a function to the replace
method. Something like this:
var result = str.replace(/\{\{(.*?)\}\}/g, function(match, token) {
return data[token];
});
The second parameter matches the first subgroup and so on.