String.Format = function()
{
// Check for arguments
if( arguments.length == 0 ) return null;
// Get the string which is the first argument
var stringToFormat = arguments[0];
for(var i=1; i < arguments.length;i++)
{
var replaceExpression = new RegExp('\\{' + (i-1) + '\\}','gm');
// Replace argument
stringToFormat = stringToFormat.replace(replaceExpression, arguments[i]);
}
// Return the formated string
return stringToFormat;
}
Alternative you can used the JavaScript prototype framework 'Template' object to do string formatting using variable names instead of argument indexes.
See http://prototypejs.org/api/template for the Template object API.
Thank you! This is great.
ReplyDelete