Replacing words in a String by letters

I've got this string :

var str:String = mySharedObject.data.theDate; 

where mySharedObject.data.theDate can contain the word January, February, March..etc (depends on which button the user clicked).

Is it possible to tell to my code to replace "January" by "1" (if mySharedObject contain the word January), "February" by "2"...etc ?

Answers


The most basic way to do what you'd like, is to the use the replace method of a string.

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

Now, you could repeat or chain together for all 12 months (eg str = str.replace("January","1").replace("February","2").replace("March","3")..etc) or you could do it in a loop:

//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); 

Now, there are a few other ways to replace strings in ActionScript that are all a little different in terms of complexity and performance, but if you're just getting started I would stick with the replace method.

The only possible caveat with replace is that it only replaces the first instance of the word, so if your string was "January January January", it would come out as "1 January January".


Need Your Help

Use of uninitialized value in die... (perl)

perl die

When I run my script, I get the error:

Flex: Animate an image how to do it in as3

flex actionscript-3 animation

i am having problems with animation. Can't realize how to animate things in flex?