JavaScript .Net like String formatting function

Just a simple extend to the JavaScript String prototype which makes things much more readable 🙂

String.prototype.beginsWith = function(str) {return (this.match("^"+str)==str)}
String.prototype.endsWith = function(str) {return (this.match(str+"$")==str)}
String.prototype.format = function() {
    var s = this,
        i = arguments.length;

    while (i--) {
        s = s.replace(new RegExp('\{' + i + '\}', 'gm'), arguments[i]);
    return s;


var str = 'Just a {0} test to {1} if things works. Really {0}, isn't it?';
alert(str.format('simple', 'see');

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.