views:

19419

answers:

8

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.

+14  A: 

Try sprintf() for JavaScript.

Gumbo
love it, works great.
Cheeso
good stuff.....
Yuval A
+1  A: 

Hi there,

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

Regards, Pooria.

Pooria
+5  A: 

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.

Chris S
+3  A: 

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.

17 of 26
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
+4  A: 

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.

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
Not an exe any more, looks pretty excellent.
Toby
+3  A: 

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")
Zippo
+2  A: 

+1 Zippo with exception that the function body needs to be as below or otherwise it appends the current string on every iteration:

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

JavaScript programmers can use String.prototype.sprintf at http://code.google.com/p/jsxt/source/browse/trunk/js/String.js. Below is example:

var d = new Date();
var dateStr = '%02d:%02d:%02d'.sprintf(
    d.getHours(), 
    d.getMinutes(), 
    d.getSeconds());
jsxt