I want this code:
function renderTemplate(temp,content){
for (var i in temp){
replace = new RegExp("["+i+"]",'g');
content = content.replace(i,temp[i]);
}
return content;
}
var temp = {'status':'ok','id':150};
var content = "your status is [status], again! your status is [status], and your id is [id], yes[id]";
alert(renderTemplate(temp,content));
To genrate me this string:
your status is ok, again! your status is ok, and your id is 150, yes 150
Instead, I get:
your ok is [status], again! your status is [status], and your 150 is [id], yes[id]
Look where the ok was placed….
you can run it here: http://jsfiddle.net/v9vzd/
Thanks
Although Adrian Lang’s fine answer should get you going, I would argue that you’re not taking the best approach. Compiling regexes from a variable can be awkward when it comes to escaping, and it’s generally slower performance-wise.
If it were me, I would take advantage of passing a function to
replace():This works because the sub-expression capture,
([^\]]+)is passed to the replacing function as the second argument — labelledkeyin our function above — and this matches anything between a literal[and].