Porting String.Format to ActionScript
One of my favorite methods in the .NET framework is the string class’s Format method. If you are unfamiliar, you can read more about it here: http://msdn.microsoft.com/en-us/library/aa331875.aspx. The .NET implementation contains numerous formatting options; however, I am only interested in the basic idea of replacing format items in a string with actual values passed to the function. This reduces the need for complex concatenations, which makes code more readable.
The ActionScript version I’ve implemented works in much the same way as its .NET counterpart. The first argument is a format string containing format items. For example, to display the current date, we may set up the following format string, “Today is {0}.” Then, we pass an array of objects to use as replacements for the format items. In our example, we would pass a new array literal with one item, [ new Date().toDateString() ]. So our entire call would look like the following:
// display today's date in the text field txtDate
txtDate.Text = StringUtils.Format( "Today is {0}." , [ new Date().toDateString() ] );
The function will return a new string that has the {0} format item replaced with the evaluated value from the Date object. It is important to note that ALL instances of {0} will be replaced, not just the first occurrence. So the function itself is very simple, but can dramatically improve the readability of code.
I have provided the source below and a link to download StringUtils.as, which has the necessary Replace function as well. The only note I would make about the code is the use of toString() on each object in the array passed to the function. This allows calling code to pass arrays containing any type of object and omit calling toString() on each instance (provided the toString() implementation is acceptable). Hopefully you find this as useful as I have!
Source:
public static function Format( formatString:String , args:Array ) : String
{
var result:String = formatString;
for (var i:int = 0; i < args.length; i++)
{
result = Replace(result, "{" + i + "}" , args[i].toString() );
}
return result;
}
