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.
Building on the previously suggested solutions:
"{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET")
outputs
If you prefer not to modify
String
's prototype:Gives you the much more familiar:
String.format('{0} is dead, but {1} is alive! {0} {2}', 'ASP', 'ASP.NET');
with the same result:
One very slightly different version, the one I prefer (this one uses {xxx} tokens rather than {0} numbered arguments, this is much more self-documenting and suits localization much better):
A variation would be:
that calls an l() localization function first.
Here's a minimal implementation of sprintf in JavaScript: it only does "%s" and "%d", but I have left space for it to be extended. It is useless to the OP, but other people who stumble across this thread coming from Google might benefit from it.
Example:
In contrast with similar solutions in previous replies, this one does all substitutions in one go, so it will not replace parts of previously replaced values.
Adding to
zippoxer
's answer, I use this function:I also have a non-prototype version which I use more often for its Java-like syntax:
ES 2015 update
All the cool new stuff in ES 2015 makes this a lot easier:
I figured that since this, like the older ones, doesn't actually parse the letters, it might as well just use a single token
%%
. This has the benefit of being obvious and not making it difficult to use a single%
. However, if you need%%
for some reason, you would need to replace it with itself:I use a small library called String.format for JavaScript which supports most of the format string capabilities (including format of numbers and dates), and uses the .NET syntax. The script itself is smaller than 4 kB, so it doesn't create much of overhead.