coffeescript version of string.format, sprintf() etc. for javascript or node.js

jiy picture jiy · Mar 27, 2012 · Viewed 11k times · Source

How do I string.format() or sprintf() in coffeescript?

Answer

Peter Lyons picture Peter Lyons · Mar 27, 2012

So there's 2 things going on here. First is interpolation, which coffeescript directly supports using double-quoted string literals and ruby style syntax like this:

"The #{speed} #{color} #{animal} jumped over the lazy dog"

That will replace the placeholders with the corresponding variables from the local scope. That's the idiomatic way to handle string interpolation in coffeescript (and ruby).

Second is the formatting, which you should probably handle separately if you want to get numbers with specific decimal places, thousands separate with commas, leading zeros, or that sort of thing. However, CoffeeScript can interpolate the formatting as well, so you could do

"Free shipping on orders over #{currency(freeShipAmount)}"

For other features with C-style formatters, have a look at JavaScript sprintf (which I found on this answer)