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


/ Published in: ActionScript 3
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  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 ] ] );
  7.  
  8. return template;
  9. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.