JavaScript String.format() method.
A while back I worked on a pretty heavy duty JavaScript interface that required, as is typical in any UI, a lot of string manipulation. I became tired of building strings with concatenation, they had a tendency to get unwieldy. I wrote this simple string formatting utility for building strings similiar to C#.
The best way to use it is to put it into an external JavaScript source file and reference it throughout the project.
Although the method has only one defined argument it will accept any number of arguments. If you provide more or less arguments than you define in your string they will not cause an error, they will be ignored.
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;
};
You can test the method with these simple tests.
//simple tests
document.write( String.format( "no tokens<br />" ) );
document.write( String.format( "one token, no args ({0})<br />" ) );
document.write( String.format( "one token, one args ({0})<br />", "arg1" ) );
document.write( String.format( "one tokens, two args ({0})<br />", "arg1", "arg2" ) );
document.write( String.format( "two tokens, two args ({0},{1})<br />", "arg1", "arg2" ) );
document.write( String.format( "two tokens swapped, two args ({1},{0})<br />", "arg1", "arg2" ) );
document.write( String.format( "four tokens interwoven, two args ({0},{1},{0},{1})<br />", "arg1", "arg2" ) );
3comments:
You can do the same with a litle less code, look my blog entry and see how I did the same thing xD
Excellent! This helped me so much :)
"{0}{1}".format("{1}","{0}");
Post a Comment