When I use Flex, I make extensive use of Resource Bundles for all but the most basic applications. In short, they allow you to keep all of your static string values (and non-string values) separated out of your code. That way, down the line it’s a very easy change when you want to localize the site in another language, rebrand it for another audience, or when a client asks you to change a button label or error message. Granted, this level of detail isn’t always necessary but I think it’s a good habit to get into even if it’s overkill for some projects.
But resource bundles can’t help you in every scenario. I often find myself needing to construct a sentence with live data inserted. For this, the resource strings are less helpful. For example, how would you write:
"At " + time + ", you received a message from " + userName + "."
With resource strings, you would have to do something like
at=At message=, you received a message from period=.
Which completely negates the whole point of using resource bundles. What to do?
Token replacement

What I really wanted was a way to inject data into the string. I’ve seen this done by use of tokens in other languages like Objective-C so I thought I’d give it a try. The result was surprisingly lightweight.
I created this utility that lets you use tokens (delimited by % signs) that can be replaced by live data when you retrieve the resource. Using this class, the example above would look more like this:
receivedMessage=At %time%, you received a message from %userName%.
// then in your code
trace(ResourceStringUtil.getResoureceStringWithTokens("receivedMessage", {time: "11:49", userName: "Mims"}));
// displays
At 11:49, you received a message from Mims.
Here’s the source code Feel free to use it and modify it for your purposes.
Hi
a similar feature is supported by the original ResourceManagerImpl class by Adobe: http://livedocs.adobe.com/flex/3/langref/mx/resources/ResourceManagerImpl.html#getString()
If a parameters Array is passed to this method, the parameters in it are converted to Strings and then substituted, in order, for the placeholders “{0}”, “{1}”, and so on, in the String before it is returned.
So you can use
receivedMessage=At {0}, you received a message from {1}.
ResourceManager.getInstance().getString( “myBundle”, “receivedMessage”, [ "11:49", "Mims" ] )
Wow! Thanks for that. I guess I should have looked closer before writing this.
I guess the way I’ve done it is a little bit nicer because it lets you insert data without being aware of what order it will appear in the string but that’s still good to know.
Cool Util Mims, thanks. I’ve seen some people pass their token values from the query string, which could compromise an app’s security. You didn’t do it but I’ve seen it done; usually with ajax though.
MK
funny, because two years ago I wrote something similar in AS2. But there wasn’t any RegExp features…that was fun :)
also, mx.utils.StringUtil.substitute()