up vote 18 down vote favorite
1

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 thousand seperator format for numbers for now, but something that handles lots of combinations (including dates) would be good.

I realise Microsoft's AJAX library provides a version of String.Format() but we don't want the entire overhead of that framework.

link|flag

6 Answers

up vote 13 down vote accepted

Try sprintf() for JavaScript.

link|flag
love it, works great. – Cheeso Dec 27 '09 at 23:43
good stuff..... – Yuval A Aug 16 at 11:56
up vote 5 down vote

I'll add my own discoveries which I've found since I asked:

Sadly it seems sprintf doesn't handle thousand seperator formatting like .NET's string format.

link|flag
up vote 4 down vote

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.

link|flag
I took a look at that library and it looks really great. I was pissed off when I saw that the download was an EXE. What the heck is that about? Didn't download. – jessegavin Apr 6 at 18:04
Not an exe any more, looks pretty excellent. – Toby Jun 17 at 19:01
up vote 3 down vote

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.

link|flag
It's actually a set by the user as a setting in the application (not the machine their on) but I'll take a look, thanks – Chris S Mar 4 '09 at 13:19
up vote 1 down vote

Hi there,

There are "sprintf" for javascript which you can find it from here: http://www.webtoolkit.info/javascript-sprintf.html

Regards, Pooria.

link|flag
up vote 0 down vote

I use this simple function:

String.prototype.format = function() {
    var formatted = "";
    for(arg in arguments) {
        formatted += this.replace("{" + arg + "}", arguments[arg]);
    }
    return formatted;
};

That's very similar to string.format:

"{0} is dead, but {1} is alive!".format("ASP", "ASP.NET")
link|flag

Your Answer

get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.