Вам нужна функция обратного вызова для replace()
.
var img_template = "<img src='{src}' width='{width}' height='{height}' title='{title}' />";
var img_info = {
src : 'http://myimage.com/img.jpg',
width: '100px',
height: '100px',
title: 'My Image'
};
// callback function will be executed for each match
var my_image = img_template.replace(/{([^}]+)}/g, function(match, group1) {
// return lookup value or the empty string
return img_info[group1] || "";
});
или в форме многократного использования:
function HtmlTemplate(html) {
this.template = html;
this.render = function(info) {
return this.template.replace(/{([^}]+)}/g, function(match, group1) {
return info[group1] || "";
});
};
}
var imgTemplate = new HtmlTemplate("<img src='{src}' width='{width}' height='{height}' title='{title}' />");
// later
var img = imgTemplate.render(img_info);