Based on @Vlad Bezden answer I use this slightly modified code because I prefer named placeholders:
String.prototype.format = function(placeholders) {
var s = this;
for(var propertyName in placeholders) {
var re = new RegExp('{' + propertyName + '}', 'gm');
s = s.replace(re, placeholders[propertyName]);
}
return s;
};
usage:
"{greeting} {who}!".format({greeting: "Hello", who: "world"})
String.prototype.format = function(placeholders) {
var s = this;
for(var propertyName in placeholders) {
var re = new RegExp('{' + propertyName + '}', 'gm');
s = s.replace(re, placeholders[propertyName]);
}
return s;
};
$("#result").text("{greeting} {who}!".format({greeting: "Hello", who: "world"}));