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!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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.
1 2 3 4 5 6 | 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.
Published at 4:26 pm on July 23rd, 2007.
Topics: Flash