ActionScript trim function

ActionScript 2.0 doesn’t have a trim function to strip whitespace from the start and end of a string. Here’s a simple function I wrote because I couldn’t find a satisfactory example on Google!

function trim(str:String):String
{
var stripCharCodes = {
code_9 : true, // tab
code_10 : true, // linefeed
code_13 : true, // return
code_32 : true // space
};
while(stripCharCodes["code_" + str.charCodeAt(0)] == true) {
str = str.substring(1, str.length);
}
while(stripCharCodes["code_" + str.charCodeAt(str.length - 1)] == true) {
str = str.substring(0, str.length - 1);
}
return str;
}

The horrible "code_" prefix hack is there because I don’t think there’s a native way to search an array or object for a key or value in ActionScript.

Update: just found this function at: frogstyle.ch. This one does a similar thing, but strips more characters.

function trim(str:String):String
{
for(var i = 0; str.charCodeAt(i) < 33; i++);
for(var j = str.length-1; str.charCodeAt(j) < 33; j--);
return str.substring(i, j+1);
}

Update: as3corelib has a static trim method in com.adobe.utils.StringUtil.

Comments