I have RTRIM; how to make LTRIM with regexp

孤人 提交于 2019-12-25 01:47:06

问题


I have RTRIM; how to make LTRIM one?

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


回答1:


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.




回答2:


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.




回答3:


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 "";
}


来源:https://stackoverflow.com/questions/556603/i-have-rtrim-how-to-make-ltrim-with-regexp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!