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.
If you are looking to handle the thousands separator, you should really use toLocaleString() from the JavaScript Number class since it will format the string for the user's region.
The JavaScript Date class can format localized dates and times.
Very elegant:
Credit goes to
(broken link)https://gist.github.com/0i0/1519811+1 Zippo with the exception that the function body needs to be as below or otherwise it appends the current string on every iteration:
I'm surprised no one used
reduce
, this is a native concise and powerful JavaScript function.ES6 (EcmaScript2015)
< ES6
How it works:
It's funny because Stack Overflow actually has their own formatting function for the
String
prototype calledformatUnicorn
. Try it! Go into the console and type something like:You get this output:
Hello, Gabriel, are you feeling OK?
You can use objects, arrays, and strings as arguments! I got its code and reworked it to produce a new version of
String.prototype.format
:Note the clever
Array.prototype.slice.call(arguments)
call -- that means if you throw in arguments that are strings or numbers, not a single JSON-style object, you get C#'sString.Format
behavior almost exactly.That's because
Array
'sslice
will force whatever's inarguments
into anArray
, whether it was originally or not, and thekey
will be the index (0, 1, 2...) of each array element coerced into a string (eg, "0", so"\\{0\\}"
for your first regexp pattern).Neat.
I use this one:
Then I call it: