用actionscript 3修剪字符串

时间:2010-05-26 03:30:17

标签: flex actionscript-3 adobe

我正在尝试从字符串的前端和末尾修剪空白区域。看起来as3没有修剪功能。任何人都知道如何做到这一点?

7 个答案:

答案 0 :(得分:24)

您在实用程序类中有一个名为trim的方法,名为StringUtil => http://livedocs.adobe.com/flex/3/langref/mx/utils/StringUtil.html#trim%28%29

答案 1 :(得分:6)

str = str.replace(/^\s+|\s+$/g, '');

答案 2 :(得分:3)

您是否查看过Adobe的文档? http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/String.html

package {
import flash.display.Sprite;

public class StringExample extends Sprite {
    public function StringExample() {
        var companyStr:String = new String("     Company X");
        var productStr:String = "Product Z Basic     ";
        var emptyStr:String = " ";
        var strHelper:StringHelper = new StringHelper();

        var companyProductStr:String = companyStr + emptyStr + productStr;
        trace("'" + companyProductStr + "'");    // '     Company X Product Z Basic     '

        companyProductStr = strHelper.replace(companyProductStr, "Basic", "Professional");
        trace("'" + companyProductStr + "'");    // '     Company X Product Z Professional     '

        companyProductStr = strHelper.trim(companyProductStr, emptyStr);
        trace("'" + companyProductStr + "'");    // 'Company X Product Z Professional'
    }
}

}

class StringHelper {

public function StringHelper() {
}

public function replace(str:String, oldSubStr:String, newSubStr:String):String {
    return str.split(oldSubStr).join(newSubStr);
}

public function trim(str:String, char:String):String {
    return trimBack(trimFront(str, char), char);
}

public function trimFront(str:String, char:String):String {
    char = stringToCharacter(char);
    if (str.charAt(0) == char) {
        str = trimFront(str.substring(1), char);
    }
    return str;
}

public function trimBack(str:String, char:String):String {
    char = stringToCharacter(char);
    if (str.charAt(str.length - 1) == char) {
        str = trimBack(str.substring(0, str.length - 1), char);
    }
    return str;
}

public function stringToCharacter(str:String):String {
    if (str.length == 1) {
        return str;
    }
    return str.slice(0, 1);
}

}

更新:哦,刚看到ItzWarty。 -.-

答案 3 :(得分:2)

查看http://jeffchannell.com/ActionScript-3/as3-trim.html

function trim( s:String ):String
{
  return s.replace( /^([\s|\t|\n]+)?(.*)([\s|\t|\n]+)?$/gm, "$2" );
}

http://www.designscripting.com/2008/11/string-utils-in-as3/有很多字符串实用程序函数,包括字符串修剪

答案 4 :(得分:2)

试试这个

str = StringUtil.trim(str);

答案 5 :(得分:1)

您应该可以使用正则表达式,例如:

var pattern:RegExp = /(\t|\n|\s{2,})/g;  
trimmedString = untrimmedString.replace(pattern, '');  

答案 6 :(得分:1)

ItzWarty的解决方案不会删除尾随空格。

Amargosh的解决方案对我来说非常有效,并且也在http://jeffchannell.com/ActionScript-3/as3-trim.html给出。

不幸的是,我没有足够的声誉来投票支持Amargosh的解决方案。

此外,我不得不删除双引号,所以这是我的修剪:

function trim( s:String ):String
{
  return s.replace(/^[\s|"]+|[\s|"]+$/gs, '');
}