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″ ) );
January 17, 2008 at 3:26 pm
This has been added into the asp.net AJAX framework for asp.net 2.0
Just do String.format the same way you would in C# or vb.net.
January 17, 2008 at 10:41 pm
Thanks for commenting. I’ll have to check that out, I wrote this function a while back in my (Classic) ASP days. Now that there are so many great-looking and free JavaScript libraries available, I wonder if any of them have this built-in too?
July 5, 2008 at 5:32 pm
Hey I know this post is pretty old, but here’s a much more succinct method I wrote that does the same thing:
String.prototype.format = function()
{
var pattern = /\{\d+\}/g;
var args = arguments;
return this.replace(pattern, function(capture){ return args[capture.match(/\d+/)]; });
}
usage: ‘{0} {1}’.format(foo, bar)
returns: “foo bar”
Enjoy!
July 5, 2008 at 5:33 pm
oops… that should be:
‘{0} {1}’.format(‘foo’,'bar’)
July 5, 2008 at 6:46 pm
Sexy implicit JavaScript behavior and Lambda action there Dan. Thanks, it’s been a while since I really looked long and hard at JavaScript, nice to see an old trick improved.