JavaScript sprintf(3)

February 15th, 2007 by Ralf S. Engelschall

Some time ago I was extremely bored by the fact that on hacking JavaScript code I had no POSIX sprintf(3) style function available. Perhaps the puristic JavaScript-only coders might see no need for this, for a Unix hacker this gap has to be filled. Hence I’ve searched for an sprintf(3) implementation and found Jan Moesen’s small sprintf(3) implementation.

Although it was limited and partly buggy, it was definitely the right direction. Hence I’ve worked off, extended, fixed and cleaned the code. And the result is a still limited, but now mature enough POSIX sprintf(3) style implementation for JavaScript in about 8KB (well, jsmin is even able to reduce it to just 3KB).

With this I can now stick to the way of string formatting I’m used to since two nearly decades. For instance, the JavaScript expression sprintf("<div>%-*.2s</div>", 4, "test") results in the string “<div>te </div>” and the JavaScript expression sprintf("<div>%#06x</div>", 10) results in the string “<div>0x000a</div>“. Voila! That’s all I wanted to see..

My sprintf() implementation you can download from the File Repository, together with a small test case.

Leave a Reply