Javascript String format(...args)

Description

Javascript String format(...args)


String.prototype.format = function format(...args) {
  let self = this.toString();

  if (!args.length) { return self; }

  const replacers = args.shift();
  if (typeof replacers !== 'object') {
    throw new Error('String.format expected an object as the first parameter');
  }//  w w w.  j ava  2s  .  c o m

  Object.keys(replacers).forEach((key) => {
    self = self.replace(new RegExp(`\{${key}\}`, 'gi'), replacers[key]);
  });

  return self;
};

Javascript String format(...args)


String.prototype.format = function (...args) {
  return this.replace(/\{(\d+)\}/g, function (m, i) {
    return args[i]
  })/*ww w.ja va 2  s  .  c om*/
}



PreviousNext

Related