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); } |
Published at 4:26 pm on July 23rd, 2007.
Topics: Flash
8 Comments
This function has been a great help. Thanks!!!
Comment by yiannis karadimas at 7:19 pm on February 10th, 2008 #link
Thanks for valuable fucntion …it saves lot of time to write again !
Comment by Baljeet at 6:20 pm on February 12th, 2008 #link
Thanks man!
Comment by yet another AS2 looney at 1:25 pm on March 11th, 2008 #link
It worked for me. Great Code. Thanks for sharing.
Comment by Suresh at 8:39 pm on August 9th, 2008 #link
Thanks! This is short and clean: The way it should be.
Comment by Greg Ferrell at 8:41 pm on August 21st, 2008 #link
Thanks a lot! It really helps and works from the forst eseye! Спасибо
Comment by quezak at 1:52 pm on August 28th, 2008 #link
Thks for this good code snippet!
Comment by pok at 6:09 pm on September 4th, 2008 #link
Thanks , nice trim methods.
Comment by Brent at 2:39 pm on October 7th, 2008 #link