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.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*

* Copy this password:

* Type or paste password here:

2,918 Spam Comments Blocked so far by Spam Free Wordpress

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>