用字母替换字符串中的单词

时间:2015-12-04 21:36:08

标签: string actionscript-3 replace str-replace

我有这个字符串:

var str:String = mySharedObject.data.theDate; 

其中mySharedObject.data.theDate可以包含单词January,February,March..etc(取决于用户点击的按钮)。

是否可以告诉我的代码更换" 1月" by" 1" (如果mySharedObject包含单词January)," February" by" 2" ...等?

1 个答案:

答案 0 :(得分:0)

执行您喜欢的操作的最基本方法是使用字符串的replace方法。

str = str.replace("January","1");

现在,您可以在所有12个月内重复或链接(例如str = str.replace("January","1").replace("February","2").replace("March","3")..etc),或者您可以循环播放:

//have an array of all 12 months in order
var months:Array = ["January","February","March","April","May"]; //etc

//create a function to replace all months with the corresponding number
function swapMonthForNumber(str:String):String {
    //do the same line of code for every item in the array
    for(var i:int=0;i<months.length;i++){
        //i is the item, which is 0 based, so we have to add 1 to make the right month number
        str = str.replace(months[i],String(i+1));
    }
    //return the updated string
    return str;
}

var str:String = swapMonthForNumber(mySharedObject.data.theDate); 

现在,还有一些其他方法可以替换ActionScript中的字符串,这些方法在复杂性和性能方面都有所不同,但如果您刚开始使用,我会坚持使用replace方法。

replace唯一可能的警告是,它只会替换该单词的第一个实例,因此,如果您的字符串为"January January January",则会显示为"1 January January"