Return to Snippet

Revision: 39609
at January 19, 2011 03:03 by mgeduld


Initial Code
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;
}

Initial URL

                                

Initial Description
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.

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

Initial Tags
template, replace, regexp

Initial Language
ActionScript 3