views:

330

answers:

3

I have RTRIM; how to make LTRIM one?

public static function rtrim(string:String):String
{
return string.replace(/\s+$/,"");
}

+2  A: 
public static function ltrim(string:String):String {
    return string.replace(/^\s+/,"");
}

Caveat: Untested! Look up the flex 3.0 documentation here. This is exactly similar to what you have, except that we use a different metacharacter to specify that we want to start searching for whitespaces (\s -- another metacharacter) from the begining(^) instead of from the end($). The + after \s tells the pattern matches to grok one or more whitespaces.

dirkgently
A: 

Wow, seriously? You're using regular expressions to remove a constant sequence of characters from the ends of a string? Really? I don't know Actionscript/Flex, but this isn't the way to go. After a quick google I found a solution which may or may not be more efficient.

sebnow
It's always fun to use things for stuff they never were meant to be used with.
dirkgently
In client-side JavaScript over 100,000 iterations in Firefox, the regular expression takes less than half the time than the example you pasted (appropriately modified).
Grant Wagner
I'm unsure exactly is wrong with using a regular expression to remove whitespace from the ends of a string. The regular expression code communicates the intent and does so declaratively (tell the computer what you want) as opposed to imperatively (tell the computer the steps to get what you want).
Grant Wagner
Regular expressions, like XML, is often used for things that it's not appropriate for. There's no reason to use something as complex as regular expressions for something as simple as removing a sequence of two characters from the beginning/end of a string. The speed difference is surprising though.
sebnow
+2  A: 

Instead of re-inventing the wheel, why not just use the StringUtil class from Adobe's as3corelib library?

Out of interest, as3corelib defines it's trim functions as follows:

public static function trim(input:String):String
{
    return StringUtil.ltrim(StringUtil.rtrim(input));
}

public static function ltrim(input:String):String
{
    var size:Number = input.length;
    for(var i:Number = 0; i < size; i++)
    {
        if(input.charCodeAt(i) > 32)
        {
            return input.substring(i);
        }
    }
    return "";
}

public static function rtrim(input:String):String
{
    var size:Number = input.length;
    for(var i:Number = size; i > 0; i--)
    {
        if(input.charCodeAt(i - 1) > 32)
        {
            return input.substring(0, i);
        }
    }
    return "";
}
LukeH
The code presented in this answer only removes spaces from the beginning and end of the line. The regular expression version removes [ \t\n\r\f\v].
Grant Wagner
@Grant, Not true, it removes all character codes < 33. Space=32, \t=9, \n=10, \r=13, \f=12, \v=11 etc so they'll all be removed. (This is Adobe's implementation, not mine, btw.)
LukeH