Python-style template strings for AS3

http://gist.github.com/613564


package
{
public class StringTemplate
{
/**
* Mimics the python template string format, eg:
*
* "blah blah %(varname)s blah blah"
*
* then you pass in a 'dict' of varnames which get
* substituted into the string when run.
*/
public static function parse(str:String, vars:Object):String
{
var re:RegExp = /\%\((\w+)\)s/g;
var match:Object;
while((match=re.exec(str)) !== null) {
if (vars.hasOwnProperty(match[1])) {
str = str.replace(match[0], vars[match[1]]);
}
}
return str;
}
}
}

Currently only handles the ‘dict of vars’ style substitution and probably doesn’t handle escaping and other edge-cases properly. Fine for a bit of quick and dirty string action though.

Posted in AS3

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s