JavaScript equivalent of Python's format() function? JavaScript equivalent of Python's format() function? python python

JavaScript equivalent of Python's format() function?


Another approach, using the String.prototype.replace method, with a "replacer" function as second argument:

String.prototype.format = function () {  var i = 0, args = arguments;  return this.replace(/{}/g, function () {    return typeof args[i] != 'undefined' ? args[i++] : '';  });};var bar1 = 'foobar',    bar2 = 'jumped',    bar3 = 'dog';'The lazy {} {} over the {}'.format(bar3, bar2, bar1);// "The lazy dog jumped over the foobar"


There is a way, but not exactly using format.

var name = "John";var age = 19;var message = `My name is ${name} and I am ${age} years old`;console.log(message);