We had just such a discussion about this on the list a couple weeks ago. 
 
Here is the solution that I use to remove leading and trailing spaces:
 
 function trim(input:String):String {
  if (input==undefined || input==null) return input; //quit now if input is not given...
  
  var len:Number = input.length;
  var start:Number = 0;
  var end:Number = len;
  while ((start < end) && (input.charCodeAt(start) <= 32)) { //increment start until first non-whitespace at start of input
   start++;
  }
  while ((start < end) && (input.charCodeAt(end - 1) <= 32)) { //decrement end until first non-whitespace at end of input
   end--;
  }
  return ((start > 0)||(end < len)) ? input.substring(start, end) : input; //return substring if start or end changed, or just return original;
 }
I based this directly off of how java's String.trim() functions.  Note that this version will also remove tabs, linefeeds and other whitespace type extras.  in fact it removes everything before the ascii-32 character in an 256 character ascii chart.

--
Ronald Kinion
253-205-3000 x5162
[EMAIL PROTECTED]


 


From: flexcoders@yahoogroups.com [mailto:[EMAIL PROTECTED] On Behalf Of Rajesh Jayabalan
Sent: Wednesday, May 18, 2005 1:30 PM
To: flexcoders@yahoogroups.com
Subject: [flexcoders] Re: string trim

Thanx
--- In flexcoders@yahoogroups.com, Matt Chotin <[EMAIL PROTECTED]> wrote:
> Here's an alternative to Tracy's that I've used:
>
> function trimString(str : String) : String
> {
>     var startIdx = 0;
>     while(str.indexOf(' ',startIdx) == startIdx)
>         ++startIdx;
>     var endIdx = str.length-1;
>     while(str.lastIndexOf(' ',endIdx) == endIdx)
>         --endIdx;
>
>     if (endIdx >= startIdx)
>     {
>         return str.slice(startIdx,endIdx+1);
>     }
>     else
>     {
>         return "";
>     }
> }




Yahoo! Groups Links

Reply via email to