String.Format() for JavaScript

.Net's String.Format is a very powerful method for working with strings and is one of my favorite utility which I have been using in C# & VB.net since long. And while working with javascript, lot many times I thought if we had something equivelent to .Net's  String.Format in javascript. Finally after goggling and taking help form few blogs I finally wrote following String.Format function into my javascript library.

String.format = function (text) {

    //check if there are two arguments in the arguments list
    if (arguments.length <= 1) {
        //if there are not 2 or more arguments there's nothing to replace
        //just return the original text
        return text;
    }

    //decrement to move to the second argument in the array
    var tokenCount = arguments.length - 2;
    for (var token = 0; token <= tokenCount; token++) {
        //iterate through the tokens and replace their
        // placeholders from the original text in order
        text = text.replace(new RegExp("{" + token + "}", "gi"),
                                                arguments[token + 1]);
    }
    return text;
};

The above code creates static function String.format and below is the working example of it:

var result = String.format("Sum of {0} and {1} is {2).", 5,6,5+6)

//This results in
result = "Sum of 5 and 6 is 11."

This functionality can also be written in inline flavor:

String.prototype.format = function () {
	var txt = this;
	for(var i=0;i<arguments.length;i++)
	{
		var exp = new RegExp('{' + (i) + '}','gm');
		txt = txt.replace(exp,arguments[i]);
	}
	return txt;
}


Usage:

var result = "Sum of {0} and {1} is {2).".format(5,6,5+6);
//This results in
result = "Sum of 5 and 6 is 11."

Related Links: