Nov 21, 2008
Code snippet: Trimming texts in AS2
From time to time some of us still have to code in oldskool ActionScript 2. A few days ago a colleague asked me for a function for trimming ‘new line’ (\n), ‘carriage return’ (\r) characters, spaces, …
So I ended up searching my archives for a code snippet to archive this functionality and look what I found:
This code takes out the characters that are defined in the character_array variable:
// remove \r , \n , & from string function trimTextChars(text_str):String { var character_array:Array = new Array(chr(13), chr(10), chr(38)); var inputstring:String = text_str; for(i=0 ; i < character_array.length ; i++) { var temp_array = inputstring.split(character_array[i]); for(j=0 ; j < temp_array.length ; j++) temp_array[j] = trim(temp_array[j]); inputstring = temp_array.join(" "); } return inputstring; }
This code removes leading and trailing spaces from a given string:
// Trim leading and trailing spaces from string function trim(txt_str):String { while (txt_str.charAt(0) == " ") txt_str = txt_str.substring(1, txt_str.length); while (txt_str.charAt(txt_str.length-1) == " ") txt_str = txt_str.substring(0, txt_str.length-1); return txt_str; }
Enjoy!