Underscore.js has a great _.template function that I would recommend using but here is one way you could solve it below:
makeTemplate is a function that generate a function that interpolates your variables. You can pass it a template string and it will generate a function that when called with an object will interpolate the properties. Processing the template first is generally more efficient than finding and replacing each time.
var makeTemplate = (function() {
var escapeMap = {
'\n' : '\\n',
'\"' : '\\\"',
'\u2028' : '\\u2028', // line separator
'\u2029' : '\\u2029' // paragraph separator
};
return function (templateString) {
// Escape Special Characters
templateString = templateString.replace(/["\n\r\u2028\u2029]/g, function(index) {
return escapeMap[index];
});
// Replace interpolation ({@foo}) variables with their object counterpart.
templateString = templateString.replace(/\{@(\w+)\}/g, '" + (obj["$1"] || "") + "');
// Return template function.
return new Function('obj', 'return "' + templateString + '";');
};
}());
Once you have your makeTemplate function you can define your html and make your template function:
var html = '<div id="targetdiv"><div class="Comments30" title="{@something1}"></div><div class="{@something2}" title="{@something3}"></div><div class="Comments30" title="{@something4}"></div></div>';
var template = makeTemplate(html);
Once you have your template function you can call the template function:
var interpolatedHtml = template({
something1 : "value1",
something2 : "value2",
something3 : "value3",
something4 : "value4"
});