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.
Just in case someone needs a function to prevent polluting global scope, here is the function that does the same:
I use this simple function:
That's very similar to string.format:
Edit: From ES6 on you could use template strings:
See Kim's answer below for details.
Original answer:
Try sprintf() for JavaScript.
Update Ok, if you really want to do a simple format method on your own, don’t do the replacements successively but do them simultaneously.
Because most of the other proposals that are mentioned fail when a replace string of previous replacement does also contain a format sequence like this:
Normally you would expect the output to be
{1}{0}
but the actual output is{1}{1}
. So do a simultaneously replacement instead like in fearphage’s suggestion.jsxt, Zippo
This option fits better.
With this option I can replace strings like these:
With your code the second {0} wouldn't be replaced. ;)
JavaScript programmers can use String.prototype.sprintf at https://github.com/ildar-shaimordanov/jsxt/blob/master/js/String.js. Below is example:
The PHPJS project has written JavaScript implementations for many of PHP's functions. Since PHP's
sprintf()
function is basically the same as C'sprintf()
, their JavaScript implementation of it should satisfy your needs.