Javascript String format(obj)

Description

Javascript String format(obj)


String.prototype.format = function(obj) {
    var prop,// w ww .ja va2 s  .  c  o  m
        regex,
        newFormat = this;
    for (prop in obj) {
        regex = new RegExp('#{' + prop + '}', 'g');
        newFormat = newFormat.replace(regex, obj[prop]);
    }
    return newFormat;
};

console.log('The oresident of the United States is #{name}?'.format({
    name: 'Obama'
}));
console.log('This is #{name} and he is #{age} years old'.format({
    name: 'Jonny',
    age: 11
}));

Javascript String format(obj)

//Problem 1. Format with placeholders
//Write a function that formats a string. The function should have placeholders, as shown in the example
//Add the function to the String.prototype

String.prototype.format = function (obj) {
    var text = this;

    for (var property in obj) {
        var regExp = new RegExp('#{' + property + '}', 'g');
        text = text.replace(regExp, obj[property]);
    }//from   ww  w  .j  a v a  2 s .c om
    return text;
}

var options = { name: 'John' };
var sentance = 'Hello, there! Are you #{name}?';

console.log(sentance.format(options));

Javascript String format(obj)

// String Interpolation
// --------------------
// Supports #name syntax for object argument
// Or $n syntax for anonymous arguments.
String.prototype.format = function(obj) {
  var key, output, arg, replacements;
  output = this.valueOf();/*from w  ww. jav  a  2s.  c  o m*/

  if(typeof obj === 'object') {
    for(key in obj) {
      output = output.replace('#' + key, obj[key]);
    }
  } else {
    replacements = 0;
    for(arg in arguments) {
      if(output !== output = output.replace('$' + replacements)) {
        replacements++;
      }
    }
  }

  return output;
}

Javascript String format(obj)

String.prototype.format = function (obj) {
    var result = this.toString();
    for (var key in obj) {
        result = result.replace(new RegExp("{{" + key + "}}", "gi"), obj[key].toString());
    }//from  www  .j  a  va2s. c  o  m
    return result;
};



PreviousNext

Related