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.
Written by Kevin Ennis
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Related Tags
#javascript
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#