Last Updated: February 25, 2016
·
2.334K
· kevincennis

Python-style string formatting in JS

Building strings with dynamic content in JavaScript is pretty gross. Start quote, end quote, concatenate, start quote, end quote...

I often find myself messing it up when I'm trying to type quickly.

This little function takes a page out of Python's book and adds string interpolation to JS.

String.prototype.format = function(){
  var args = arguments
  return this.replace(/\{\{|\}\}|\{(\d+)\}/g, function (m, i) {
    if (m == "{{") return "{"
    if (m == "}}") return "}"
    return args[i]
  })
}

And here's how you use it:

var count = 'Three', animal = 'mice', verb = 'run', output

output = '{0} blind {1}. {0} blind {1}. See how they {2}.'.format(count, animal, verb)

It's worth noting that the performance of this function isn't great compared to concatenation - so if you're doing a lot of work with strings, this probably isn't a great choice. But is sure is nicer to write.