Left trim and right trim actionScript functions
These useful functions (lTrim and rTrim) are available in almost all programming languages yet not in actionScript, so here’s how to write ones yourself:
lTrim is easier, so we’ll start with that:
[as]
function lTrim(txt:String):String {
while
(txt.charAt(0)==” ”
||txt.charAt(0)==”\t”
|| txt.charAt(0)==”\n”
|| txt.charAt(0)==”\r”
) {
txt=txt.substring(1,txt.length-1);
}
return txt;
}
//usage example:
trace(lTrim(” here’s a text to trim”));// outputs : here’s a text to trim
[/as]
Pretty much straight forward, the function accepts a string as argument and returns a string, it checks whether the first character is a space, tab, or newline character and simply cuts it out and runs the same check on the resulting substring until there are no white spaces left at the leftmost end of the string.
Now for the slightly harder rTrim function,
[as]
function rTrim (txt:String):String {
while (txt.charAt(txt.length-1)==” ” ||txt.charAt(txt.length-1)==”\t” || txt.charAt(txt.length-1)==”\n” || txt.charAt(txt.length-1)==”\r”){
txt=txt.substring(0,txt.length-1);
}
return txt;
}
trace(rTrim (“rtrim this please \n\r “)+”delimiter”);//outputs : rtrim this pleasedelimiter
[/as]
The logic is very similar, feel free to use these wherever you like.
I would recommend using these as part of a class for string manipulation.
Btw, these functions are AS2 and AS3 compatible.