Trimming Whitespace : trim « String « Flash / Flex / ActionScript






Trimming Whitespace

 

package{
  import flash.display.Sprite;
  
  public class Main extends Sprite{
    public function Main(){
        var example:String = "\n\r\f\ta string\t\t\n\n";
        
        trace( "this string value is: " + example + "<end>" );
        
        example = trim( example );
        
        trace( "this string value is: " + example + "<end>" );
        
        trace( trim( "\n  \r\ta string\t\t\n\n" ) + "<end>" );


    }
    public static function isWhitespace( ch:String ):Boolean {
      return ch == '\r' || 
             ch == '\n' ||
             ch == '\f' || 
             ch == '\t' ||
             ch == ' '; 
    }
    
    public static function trim( original:String ):String {
    
      var characters:Array = original.split( "" );
    
      for ( var i:int = 0; i < characters.length; i++ ) {
        if ( isWhitespace( characters[i] ) ) {
          characters.splice( i, 1 );
          i--;
        } else {
          break;
        }
      }
      return characters.join("");
    }
  }
}

        








Related examples in the same category