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.
2 Responses to String format with tokens in Actionscript 3
-
Calendar
May 2013 M T W T F S S « Jul 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 30 31 -
Meta






You should check out StringUtil.substitute as that does the same thing. Its in the package mx.utils.StringUtil
I know this is an old post, but I couldn’t remember the function call (‘substitute’) and when I tried to google an answer this page came up.
Thanks for the comment Kenneth. Yes, you’re right, but the mx.utils package is only available if you’re using Flex, and not just AS3 with Flash and I wrote it before I’d started using Flex. The source for that function can be found at http://opensource.adobe.com/svn/opensource/flex/sdk/branches/3.x/frameworks/projects/framework/src/mx/utils/StringUtil.as – it also uses a regular expression so is fairly similar.