/ Published in: ActionScript 3
This simple construct allows you to replace parts of a string with items in a hash table (e.g. and Object).
Example:
var replacements : Object = { SPEED : "slow", ADJECTIVE : "green", VERB: "slithers" };
var template: String = "The %{SPEED} %{ADJECTIVE} fox %{VERB} over the %{ADJECTIVE} dog.";
trace( makeReplacements( template, replacements ) );
//output: The slow green fox slithers over the green dog.
Expand |
Embed | Plain Text
function makeReplacements( template : String, replacements : Object ) : String { var regExp : RegExp = new RegExp( "(%\{(.*?)})","" ); var match : Array; while( match = regExp.exec( template ) ) template = template.replace( regExp, replacements[ match[ 2 ] ] ); return template; }
Comments
Subscribe to comments
You need to login to post a comment.

Incidentally, it pisses me off that I have to run the regular expression twice (lines 5 and 6). Originally, I thought I could do it like this:
var regExp : RegExp = new RegExp( "(%{(.*?)})","g" ); //NOTE the "g" template = template.replace( regExp, replacements[ "$2" ] );
The "g" (global) switch will do all the replacements at once, so no need for a while loop. The $2 refers to the second (inner) parenthesis in the RegExp: (.*?). That will match the word inside the %{ } construct. The 2 in match[ 2 ], above, is doing the same thing. So if the construct is %{ADJECTIVE}, "$2" and match[ 2 ] match ADJECTIVE.
However, what I discovered is that Actionscript won't let you pass the "$2" into another function or use it as a key to a hash. So replacements[ "$2" ] inside a replace() won't get parsed to replacements[ "ADJECTIVE" ]. It will literally look for replacements.$2.
That forced me to first extract ADJECTIVE, with the exec() method, and then to use that string directly in the replace() command. Not a huge deal to run a RegExp twice, but not ideal in terms of optimization.
Darn.
If anyone knows a way around this, let me know.