Posted By

mgeduld on 01/19/11


template replace regularexpressions String regexp strings RegularExpression

Versions (?)

Who likes this?

1 person have marked this snippet as a favorite


Template system (replace items in a string with items from a hash)

 / 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).


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.

  1. function makeReplacements( template : String, replacements : Object ) : String
  2. {
  3. var regExp : RegExp = new RegExp( "(%\{(.*?)})","" );
  4. var match : Array;
  5. while( match = regExp.exec( template ) )
  6. template = template.replace( regExp, replacements[ match[ 2 ] ] );
  8. return template;
  9. }

Report this snippet  


RSS Icon Subscribe to comments
Posted By: mgeduld on January 19, 2011

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.


If anyone knows a way around this, let me know.

You need to login to post a comment.