One of the annoying issues with Javascript is when it comes to formatting strings with values from variables usually you end up with the following:
var someValue = 100;
var anotherValue = 555;
alert('someValue is ' + someValue + ' and anotherValue is ' + anotherValue);
This ends up being hard to read and also prone to errors when operators/quotes are missed or not matched properly, if this was C# we could do the following:
var someValue = 100;
var anotherValue = 555;
Console.WriteLine(String.Format("someValue is {0} and anotherValue is {1}", someValue, anotherValue));
This is much nicer it would be better if we had string interpolation but hey-ho maybe in a future version.
One of the great things about the dynamic nature of Javascript is that you can extend any of it’s types as they are all objects using the prototype keyword, so we can extend the String object and also make use of the arguments object to allow any number parameters to be passed in:
String.prototype.format = function()
{
var content = this;
for (var i=0; i < arguments.length; i++)
{
var replacement = '{' + i + '}';
content = content.replace(replacement, arguments[i]);
}
return content;
};
This allows us to replace the first code example with this:
var someValue = 100;
var anotherValue = 555;
alert('someValue is {0} and anotherValue is {1}'.format(someValue, anotherValue));
Which I think reads better than the static Format method as C# does not have built-in support for doing the following "test {0}".Format(123).
There is also String.format in the MicrosoftAjax.js.
Comment by Anonymous — November 5, 2011 @ 6:59 pm