- Train of Thoughts - http://trainofthoughts.org/blog -

JavaScript sprintf(3)

Posted By Ralf S. Engelschall On Thursday, February 15, 2007 @ 22:53 In Hacking,JavaScript | 3 Comments

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 [1].

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 [2] 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 [2], together with a small test case.


Article printed from Train of Thoughts: http://trainofthoughts.org/blog

URL to article: http://trainofthoughts.org/blog/2007/02/15/javascript-sprintf/

URLs in this post:

[1] sprintf(3) implementation: http://jan.moesen.nu/code/javascript/sprintf-and-printf-in-javascript/

[2] POSIX sprintf(3) style implementation for JavaScript: http://trainofthoughts.org/blog/repo/dirview?d=javascript

Copyright © Ralf S. Engelschall, All Rights Reserved.