Javascript String sprintf()

Description

Javascript String 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]);
  }//w  w w.j ava 2 s. com
  return formatted;
};

Javascript String sprintf()

String.prototype.sprintf = function() {
  var d = this + "";
  var a = Array.prototype.slice.call(arguments);
  var c = true;/*from  w  w  w.  j av  a2  s .c om*/
  if (d.indexOf("%s", 0) != -1) {
    c = false
  }
  if (a.length === 1) {
    if (c) {
      return d.replace(/%1$s/g, a[0])
    } else {
      return d.replace(/%s/g, a[0])
    }
  } else {
    for (var b = 0; b < a.length; b++) {
      var e = b + 1;
      if (c) {
        d = d.replace("%" + e + "$s", a[b])
      } else {
        d = d.replace("%s", a[b])
      }
    }
  }
  return d
};

Javascript String 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();//ww  w. j  a v  a2 s  .com
 });
 if(text.length) result=result+text.join('');
 return result;
};

Javascript String sprintf()

String.prototype.sprintf = function(){
 if(arguments.length === 0)
  return this;/* w w w .ja v  a  2  s. co m*/
 var data = this;
 for(var k=0; k<arguments.length; ++k){
  switch(typeof(arguments[k])){
   case 'string':
    data = data.replace(/%s/, arguments[k]);
    break;
   case 'number':
    data = data.replace(/%d/, arguments[k]);
    break;
   case 'boolean':
    data = data.replace(/%b/, arguments[k] ? 'true' : 'false');
    break;
  }
 }
 return data;
}



PreviousNext

Related