AS3 Quicktip – Reversing a String With one Line of Code

ActionScipt 3 Quick Tip of the Day: How to reverse a string with one line of code.

I had the thought the other day – Is it possible to reverse a string in Flash/Flex with only one line of ActionScript Code?

I determined that it was. And here is the result of my ActionScript conjuring.

var myString:String = “ActionSript 3”;
trace(myString.split(“”).reverse().join(“”));
//Output – 3 tpirSnoitcA

Wondering what this is actually doing? Here is the explanation:

split(“”)

split() takes any string and separates it it based on the value that you pass in the parenthesis. This value is called the delimiter. For example, if I had a string “1!2!3” and split that string using an exclamation mark as the delimiter then I would have an array that includes the elements ["1","2","3"]. If I used “2” as the delimiter then the array would look like this ["1!","!3"]. Because I am not using a delimiter, just empty quotes, the string is split on each character. split() and split("") are not the same. split() without empty quotes will split on nothing and you will get an array with only one element which is the entire word.

reverse()

reverse() is a method that will take an array and and reverse the order. An array like this var myArray:Array = ["a","b","c"] will trace out as c,b,a if you use the following code trace(myArray.reverse());

join(“”);

join() will combine the elements from an array and create a string. The parameter that you pass it is called a separator and will be used to separate all the elements within the string. I use the empty string again in my code so that there will be no separation between the letters of the word. Without putting in the empty quotes you will get the result of 3, ,t,p,i,r,S,n,o,i,t,c,A with a comma separating each character including the space.

So in essence apply functions to the result of the previous function all in one line.  I take a string and split each letter into an array element, reverse that array and then join all of the separate elements back into a single word.

And that is your ActionScript 3 quicktip of the day.

As Always Happy Flashing

4 thoughts on “AS3 Quicktip – Reversing a String With one Line of Code

  1. you can use it for changing or deleting letters too:

    var myString:String = “ActionScript 3”;
    trace(myString.split(“i”).join(“j”));
    //Output – ActjonScrjpt 3

    var myString:String = “ActionScript 3”;
    trace(myString.split(“i”).join(“”));
    //Output – ActonScrpt 3

  2. Hah, very nice. I use array and string methods in conjunction nearly every day, and I was looking up some convoluted way to do this. I completely bypassed this!

    Thank ye!

  3. GREAT! i was trying to do this, but always i got the comma….. i didnt know that join do this…..

    thank you from Brazil

Comments are closed.