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);

jsfiddle - link


tl;dr

foo = (a, b, c) => `The lazy ${a} ${b} over the ${c}`

Why template strings alone aren't enough

ES6 template strings provide a feature quite similar to pythons string format. However, you have to know the variables before you construct the string:

var templateString = `The lazy ${bar3} ${bar2} over the ${bar1}`;

Why format?

Python's str.format allows you to specify the string before you even know which values you want to plug into it, like:

foo = 'The lazy {} {} over the {}'

bar1 = 'foobar'
bar2 = 'jumped'
bar3 = 'dog'

foo.format(bar3, bar2, bar1)

Solution

With an arrow function, we can elegantly wrap the template string for later use:

foo = (a, b, c) => `The lazy ${a} ${b} over the ${c}`

bar1 = 'foobar';
bar2 = 'jumped';
bar3 = 'dog';

foo(bar3, bar2, bar1)

Of course this works with a regular function as well, but the arrow function allows us to make this a one-liner. Both features are available in most browsers und runtimes:

  • Can I use template literals?
  • Can I use arrow functions?

Looking for an answer for the same question, I just found this: https://github.com/davidchambers/string-format, which is "JavaScript string formatting inspired by Python’s str.format()". It seem it's pretty much the same as python's format() function.