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

  1. Kenneth says:

    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.