Nodejs String Sprintf sprintf

Here you can find the source of sprintf

Method Source Code

String.prototype.sprintf = 
String.prototype.format = function(){
    var arr = Array.prototype.slice.call( arguments, 0 ),
        i = 1,//from  w  w w.  j a v  a 2s . c o m
        ii = arr.length,
        s = this;

    s = s.replace( /%s/g, function(){
        return '{%' + i++ + '%}';
    });

    i = 0;
    while( i < ii ){
        s = s.replace( 
            new RegExp( '{%' + (i+1) + '%}', 'g' ),
            arr[ i++ ] 
        );
    }
    return s;
}

Related

  1. sprintf()
    String.prototype.sprintf = function() {
      var formatted = this;
      for (var i = 0; i < arguments.length; i++) {
        var regexp = new RegExp('\\{'+i+'\\}', 'gi');
        formatted = formatted.replace(regexp, arguments[i]);
      return formatted;
    };
    
  2. sprintf()
    String.prototype.sprintf = function () {
      if(!arguments.length) return this.split('%s').join('');
      var text=this.split('%s'),result=text.shift();
      $.each(arguments, function(i, value){
        if(!text.length) return result;
        result = result + value+text.shift();
      });
      if(text.length) result=result+text.join('');
      return result;
    ...