Flash Action Script 3: String Substitution Utility Class
May 22, 2011

Here’s a small class that does string substitution, inspired by printf function in C. You can pass an Object into the function and it will search and replace the content of stringwith values of the objects.

stringFormat is a String object that you want to fill with replacements.
substituteData is an Object containing the replacement data.

The code is shown below. It simpy iterates each of the properties of the substituteData and replaces all of its occurrences in stringFormat.

package com.permadi.utils
	public class StringUtil
		public static function substitute(stringFormat:String, substituteData:Object):String
			for (var key:String in substituteData)
				var keyValue:String=substituteData[key];
				var lastString:String;
				// Replace all occurences
					string=string.replace("%<"+key+">", keyValue);
				while (lastString!=string);
			return string;


stringFormat="%<firstName> %<lastName> has scored %<score>."
substituteData:Object={firstName: "John", lastName: "Doe", score: 400};

// Produces: John Doe has scored 400.
StringUtil.substitute(stringFormat, substituteData);

Download example.