BootDB

Code | Open Source | Web

Sprintf Equivalent in Javascript

Below are the two methods by which we can emulate sprintf in Javascript directly to console.log and String.format:

console.log approach:

(function() {

    var logger = console.log;

    console.log = function() {

        var format = function(str, args) {
            logger(args);
            return str.replace(/{(\d+)}/g, function(match, number) {
                return typeof args[number] != 'undefined' ? args[number] : match;
            });
        };
        var inputs = Array.prototype.slice.call(arguments);
        logger(format(inputs.shift(), inputs));
    }

})()

console.log("Hello {1}", 10, 100);</pre>
<p></p>


String.format approach:


    if (!String.prototype.format) {
      String.prototype.format = function() {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function(match, number) { 
          return typeof args[number] != 'undefined'
            ? args[number]
            : match
          ;
        });
      };
    }
    "{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET");