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];
});
};
// see it in action
$(function(){
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
]));
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.