I'm looking for a good JavaScript equivalent of the C/PHP printf()
or for C#/Java programmers, String.Format()
(IFormatProvider
for .NET).
My basic requirement is a thousand separator format for numbers for now, but something that handles lots of combinations (including dates) would be good.
I realize Microsoft's Ajax library provides a version of String.Format()
, but we don't want the entire overhead of that framework.
I have a solution very close to Peter's, but it deals with number and object case.
Maybe it could be even better to deal with the all deeps cases, but for my needs this is just fine.
PS: This function is very cool if you are using translations in templates frameworks like AngularJS:
Where the en.json is something like
For Node.js users there is
util.format
which has printf-like functionality:I'll add my own discoveries which I've found since I asked:
Sadly it seems sprintf doesn't handle thousand separator formatting like .NET's string format.
I have a slightly longer formatter for JavaScript here...
You can do formatting several ways:
String.format(input, args0, arg1, ...)
String.format(input, obj)
"literal".format(arg0, arg1, ...)
"literal".format(obj)
Also, if you have say a ObjectBase.prototype.format (such as with DateJS) it will use that.
Examples...
I've also aliased with .asFormat and have some detection in place in case there's already a string.format (such as with MS Ajax Toolkit (I hate that library).
From ES6 on you could use template strings:
Be aware that template strings are surrounded by backticks ` instead of (single) quotes.
For further information:
https://developers.google.com/web/updates/2015/01/ES6-Template-Strings
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings
Note: Check the mozilla-site to find a list of supported browsers.
For those who like Node.JS and its
util.format
feature, I've just extracted it out into its vanilla JavaScript form (with only functions that util.format uses):Harvested from: https://github.com/joyent/node/blob/master/lib/util.js