ActionScript
Flash Action Script 3: String Substitution Utility Class
May 22, 2011
0
Share this:Share on FacebookTweet about this on TwitterShare on TumblrPin on PinterestShare on Google+

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.

Parameters:
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
				do
				{
					lastString=string;
					string=string.replace("%<"+key+">", keyValue);
				}
				while (lastString!=string);
			}
			return string;
		}
	}
}

Example:

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.

Share this:Share on FacebookTweet about this on TwitterShare on TumblrPin on PinterestShare on Google+
Write your comment here ...

Leave a Reply