Friday, 10 June 2011

Javascript: format() string extension for easy formatting!

Here's a simple javascript string extension for easy string formatting


Code Snippet
// Example:
//
//    var testString = "Hey {0}, this is a pretty {1} string formatter. I hope you have {2} with it!".format("guys", "cool", "fun");
//    alert(testString);
//
// String.format extension for easy formatting
String.prototype.format = function () {
    var s = this,
        i = arguments.length;
 
    while (i--) {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
    }
    return s;
};

No comments: