Javascript String format(params)

Description

Javascript String format(params)


String.prototype.format = function(params)
{
   var content = this;
   for (var i=0; i < params.length; i++)
   {//from   w w w .  j av a 2s .  c  o m
        var replacement = '{' + i + '}';
        content = content.replace(replacement, params[i]);  
   }
   return content;
}

Javascript String format(params)

String.prototype.format = function(params){
  var formatted = this;
  var fn = function(key, value){
    var regexp = new RegExp('\\{' + key + '\\}', 'gi');
    formatted = formatted.replace(regexp, value);
  };/*from w w  w  .j  a va2  s  . c o m*/

  if (typeof(params) == 'object') {
    for (var x in params) {
      fn(x, params[x]);
    }
  } else {
    for (var i = 0; i < arguments.length; i++) {
      fn(i, arguments[i]);
    }
  }
  return formatted;
};

Javascript String format(params)

console.log("Start adding extensions.");
//format string/*from   w  w  w .  jav a  2s .c  o  m*/
//reg and replace
String.prototype.format =  function(params){
    
    var reg = /{(\d+)}/gm;
    return this.replace(reg, function(match,sub){
            return params[sub];
        });
}

String.prototype.endWith = function (str){
    return (this)&&((this.indexOf(str, this.length -1)) === (this.length -1));
}
console.log("Extensions were added.");

Javascript String format(params)

// e.g. '{last}, {first}'.format({first: 'John', last: 'Doe'})
//       => 'Doe, John'
String.prototype.format = function(params) {
  if (!params) {throw new Error('No arguments passed');}
  return this.replace(/\{([a-zA-Z0-9]+)\}/g, function() {
    var key = arguments[1];
    if (params.hasOwnProperty(key)) {
      return params[key];
    } else {//from   w ww .  j  a va2 s .com
      return arguments[0];
    }
  });
};



PreviousNext

Related