Cacomania: sprintf in JavaScript

Cacomania

sprintf in JavaScript

Guido Krömer - 20. November 2012 - Tags:

This is my implementation of a sprintf like function in JavaScript. It does not support any fancy number formatting and the replacement character (%) could be replaced, too. But sometimes it is just good enough.

String.prototype.sprintf = function () {
    var string = this;
    for (var i = 0; i < arguments.length; i++) {
        string = string.replace('%', arguments[i]);
    }
    return string;
}

My sprintf is a method of the string "class", so the call would be myString.spintf(1, 2, 3) and not like in c: sprintf(myVar, 1, 2, 3):

console.log('a: % b: % c: % d: %'.sprintf('A'));
console.log('a: % b: % c: % d: %'.sprintf('A', 'B'));
console.log('a: % b: % c: % d: %'.sprintf('A', 'B', 'C'));
console.log('a: % b: % c: % d: %'.sprintf('A', 'B', 'C', 'D'));

Here is the output produced by the code above:

$ node sprintf.js 
a: A b: % c: % d: %
a: A b: B c: % d: %
a: A b: B c: C d: %
a: A b: B c: C d: D

So have fun using and modifying it.