Thursday 6 June 2013

sprintf in JavaScript

String.prototype.sprintf = function(a) {
    if (a.length) {
        var i = -1; // start at minus 1
        return this.replace(/\%(d|s|f)/gi, function(match, type){
            i++; // increment
            if (type == "d") return parseInt(a[i]);
            if (type == "f") return parseFloat(a[i]);
            if (type == "s") return a[i].toString();
        });
    }
}

var s = "Foo is %d times Blah which is %d. However, you might need %f %s";
console.log(s.sprintf([2, 4, "3.453", "shovels"]));

No comments:

Post a Comment

Disable Caching Drupal 8

1. Copy and rename the sites/example.settings.local.php to sites/default/settings.local.php: $ cp sites / example . settings . local . ph...