Clone wiki

format.js / Home

What is inside?

Many of you, like me, have tried to implement string.Format in javascript. After googling, you'll find that there are just a few, limited, incomplete implementations on the net, most of which just provide the {#} functionality. Frequently I needed some more features like {#:format} pattern. The formatting mechanism is somewhat complicated in CLR (C#, VB.NET...). I started by implementing the number and date/time formatting. The current version implements most of it, but not the one-letter formatting, that is, you can use {0:##.#0} but not {0:g} . The other interesting feature of the project is Culture support. You can add you favorite cultures and the code will use it as like C# CultureInfo parameter in stirng.Format. Since I am Persian, there are currently Invariant and Persian cultures added. You can easily add more by just declaring string constants. Also, the other attractive feature that is not even supported in C#, is named placeholders. You can use Ruby-like name placeholders instead of number (order) placeholders.


setCulture('fa-IR'); // You can set the culture at any time.

alert(String.format('{0} and {1:00}',5, 6)); // Shows '5 and 06'
alert(String.format('@{a:##} and @{b}',{a: 5, b: 6})); // Shows '5 and 6'
alert(String.format('{0:yyyy/MM/dd h:mm:ss}', new Date()));