Thursday, November 15, 2007

String.Format() JavaScript equivalent to .NET

Here is a JavaScript function to format strings on the Client-Side as if you were using in the the .NET String.Format() method in your code-behind.




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.

1 comment: