Here's a little bit of javascript that I came up with to aid in formatting strings.
String.prototype.format = function()
{
var str = this;
for(var i=0;i<arguments.length;i++)
{
var re = new RegExp('\\{' + (i) + '\\}','gm');
str = str.replace(re, arguments[i]);
}
return str;
}
This will allow you to call the format() method on any string and pass in replacement parameters. Here's an example:
var firstName = 'Ray';
var lastName = 'Houston';
var hello = 'Hello. My name is {0} {1}.'.format( firstName, lastName );
If you don't like the way that looks (and want a more .NET looking
syntax), you can create a static method on the String type like so:
String.format = function()
{
if( arguments.length == 0 )
return null;
var str = arguments[0];
for(var i=1;i<arguments.length;i++)
{
var re = new RegExp('\\{' + (i-1) + '\\}','gm');
str = str.replace(re, arguments[i]);
}
return str;
}
Then the example can be written as:
var firstName = 'Ray';
var lastName = 'Houston';
var hello = String.format('Hello. My name is {0} {1}.', firstName, lastName);
One thing this method doesn't do is that it doesn't
allow for escaping '{' or '}' characters. It will still replace {{0}}
instead of skipping it like .NET does.