C# string format in JS


The string format function in C# can be handy in JavaScript.

String.prototype.format = function() {
    var regex = /\{(\d)}/g;
    var text = this;
    while (match = regex.exec(text)) {
        text = text.replace(match[0], arguments[match[1]]);
    }
    return text;
};

I use regular expressions to match numbers with curly braces and then loop through the matches and call string replace.

Usage:

var color = 'blue';
'{0} is {1}'.format('the sky', color);
blog comments powered by Disqus
Fork me on GitHub