JS formatString

PHP sprintf implementation in JavaScript

by Marius Bogdan

HTML

<div id="alfa">-alfa-</div>
<hr>
<div id="beta">-beta-</div>
<hr>
<div id="gama">-gama-</div>

JavaScript

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
  ]));
});