Many times you want to use a string as a template and do a replace just like you do it with sprintf
function in PHP. Unfortunately, javascript don't provide a sprintf function. But, since any string is a String object type, we can extend it and add our own sprintf functionality.
Using the following example that you can test it on JsFiddle you'll have your own sprintf (format named here) function:
String.prototype.formatString = function(){
// get function arguments
var args;
if (typeof arguments[0] === 'object') {
args = arguments[0];
} else {
args = arguments;
}
// replace variables in string
return this.replace(/{([a-z_\d+]+)}/g, function(match, index){
// return replaced variable
return args[index];
});
};
Now, the usage of our newly created function is very simple. Here is an example:
var data = {
name: "John Doe",
info: "Software Engineer"
};
var tpl = '<div><h3>{name}</h3><h5>{info}</h5></div>';
var tpl2 = '<div><h3>{0}</h3><h5>{1}</h5></div>';
// use with object
$('#alfa').html(tpl.formatString(data));
// use with direct elements
$('#beta').html(tpl2.formatString(data.name, data.info));
// use with array
$('#gama').html(tpl2.formatString([
data.name,
data.info
]));