r/javascript • • Jan 28 '12

how come javascript doesn't have printf?

0 Upvotes

13 comments sorted by

View all comments

1

u/joshuag Jan 28 '12 edited Jan 28 '12

Here's a quick and dirty sprintf implementation that I wrote.

You can have it.

String.prototype.sprintf = function(){
       output = this.toString();
       for(var i=0;i < arguments.length;i++){
           asNum = parseFloat(arguments[i])
           if(asNum || asNum == 0){
                   suffix = (asNum > 1 || asNum == 0)?"s":""
                   output = output.replace(/%s {1}(\w+)\(s\){1}/, "%s $1" + suffix)
               }
               output = output.replace("%s", arguments[i])
           }
       return output;
    }

I'm not sure of all the implementation details of the original sprintf. I just needed a quick way to print into a string quickly. I also added a shortcut that will detect numeric arguments and optionally pluralize words for you.

so:

  "I have %s item(s) but only %s thing(s)".sprintf(3, 1)

results in the string:

  "I have 3 items but only 1 thing"

EDIT: I just saw this (http://www.diveintojavascript.com/projects/javascript-sprintf) further down the page. It's a much better, not-so-dirty implementation of sprintf. Use that.

1

u/bart2019 Jan 28 '12

"%s" is only the simplest use for (s)printf, and the one the least missed.

A more useful use for (s)printf in other languages is to format numbers with "%f", for example "%.3f" to get exactly 3 decimals.

But Javascript has a nice alternative: Number.toFixed(decimals):

var n = 1.123456789; alert(n.toFixed(3));   // 1.123

1

u/joshuag Jan 29 '12

I'm not sure of all the implementation details of the original sprintf. I just needed a quick way to print into a string quickly.

I understand and appreciate the urge to correct someone on the internet, though, so thank you for the elucidation.