javascriptformatstring-interpolation

JavaScript equivalent of Python's format() function?


Python has this beautiful function to turn this:

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

foo = 'The lazy ' + bar3 + ' ' + bar2 ' over the ' + bar1
# The lazy dog jumped over the foobar

Into this:

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

foo = 'The lazy {} {} over the {}'.format(bar3, bar2, bar1)
# The lazy dog jumped over the foobar

Does JavaScript have such a function? If not, how would I create one which follows the same syntax as Python's implementation?


Solution

  • 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"