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