7

I have following snippet of javascript code:

var someValue = 100;
var anotherValue = 555;
alert('someValue is {0} and anotherValue is {1}'.format(someValue, anotherValue));

getting following error:

Uncaught TypeError: undefined is not a function

what am i missing, here ?

navyad
  • 3,752
  • 7
  • 47
  • 88
  • There is no native string format method in Javascript. See: [JavaScript equivalent to printf/string.format](http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format), [String.Format in javascript?](http://stackoverflow.com/questions/2534803/string-format-in-javascript) – user Aug 10 '14 at 09:14

2 Answers2

17

String.format is not a native String extension. It's pretty easy to extend it yourself:

if (!String.prototype.format) {
  String.prototype.format = function(...args) {
    return this.replace(/(\{\d+\})/g, function(a) {
      return args[+(a.substr(1, a.length - 2)) || 0];
    });
  };
}
// usage
console.log("{0} world".format("hello"));
.as-console-wrapper { top: 0; max-height: 100% !important; }

[Update 2020]

It's not that fashionable anymore to extend native objects. Although I don't oppose it (if used carefully) a format-function can do exactly the same, or you can use es20xx template literals (see MDN).

// no native String extension
const someValue = 100;
const otherValue = 555;
const format = (str2Format, ...args) => 
  str2Format.replace(/(\{\d+\})/g, a => args[+(a.substr(1, a.length - 2)) || 0] );
console.log(format("someValue = {0}, otherValue = {1}", someValue, otherValue));

// template literal
console.log(`someValue = ${someValue}, otherValue = ${otherValue}`);
.as-console-wrapper { top: 0; max-height: 100% !important; }
KooiInc
  • 119,216
  • 31
  • 141
  • 177
6
String.format = function() {
            var s = arguments[0];
            for (var i = 0; i < arguments.length - 1; i += 1) {
                var reg = new RegExp('\\{' + i + '\\}', 'gm');
                s = s.replace(reg, arguments[i + 1]);
            }
            return s;
        };


var strTempleate = String.format('hello {0}', 'Ortal');
Ortal Blumenfeld Lagziel
  • 2,415
  • 3
  • 23
  • 33