String format with tokens in Actionscript 3
There is a great thing you can use in C#.NET (the static String.Format method) to easily format strings. It gives an easily human readable string, rather than having to use + operators all over the place with a complex concatenation, which makes it tricky to see whats going on. Here is something similar I’ve built for Actionscript.
First off, here is the implementation from C#. (This outputs ‘Hi Ian, welcome to http://www.ediblecode.com/. Thanks for visiting, – edibleCode.’)
return String.Format("Hi {0}, welcome to {1}. Thanks for visiting, - {2}."
, "Ian"
, "http://www.ediblecode.com/"
, "edibleCode");
Here is the Actionscript source code for the function. It uses a regular expression to search for tokens in the format {0}, {1} etc, and replaces them with the correspoinding string in the list of arguments passed in.
import com.chewtinfoil.utils.StringUtils;
public class StringUtil
{
public static function formatString(original:String, ...args:*):String
{
var replaceRegex:RegExp = /\{([0-9]+)\}/g;
return original.replace(replaceRegex, function():String {
if(args == null)
{ return arguments[0]; }
else
{
var resultIndex:uint = uint(StringUtils.between(arguments[0], '{', '}'));
return (resultIndex < args.length) ? args[resultIndex] : arguments[0];
}
});
}
}
And here is the implementation:
return StringUtil.formatString("Hi {0}, welcome to {1}. Thanks for visiting, - {2}."
, "Ian"
, "http://www.ediblecode.com/"
, "edibleCode");
As you probably noticed, it uses a really useful class that you can download for free from gskinner.com – com.chewtinfoil.utils.StringUtils – I’d definitely recommend it.
The String.Format method in C# is a lot more powerful than this, in that it allows formatting of numbers and dates and so on, but this Actionscript function is a good start for simple token replacement.
-
Calendar
February 2012 M T W T F S S « Feb 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 -
Meta





