Linkbar

Saturday, 15 August 2009

In this tutorial you will learn how to reverse a string in Actionscript 3.0. You need to use the following three methods to reverse a string: split(), reverse() and join(). Some knowledge of basic buttons is also needed for this tutorial. I have created a simple Flash app where you enter your message you wish to reverse, and the result get displayed in an output textbox.

Reversing a string in Actionscript 3

Step 1

Open a new Flash AS3 file.Select the text tool with input text and drag a textbox like below. I have also checked the ‘show border around text’ button, and included the message “Enter message” above the static textbox.

Step 2

Drag another textbox but this time select dynamic text. Again I have also checked the ‘show border around text’ button, and included the message “Reversed Message” above the dynamic textbox.

Step 3

Give your textboxes the following instance names accordingly: input_txt and output_txt. The ‘input_txt’ is for the input textbox, and the ‘output_txt’ is for the dynamic textbox.

Step 4

Create a button on the stage if you don’t know how to create checkout the basic buttons tutorials. I have basic black button with the text ‘reverse’ in the centre of the button.

Convert your button a symbol (F8) and give it the instance name: “change_btn”.

Step 5

On the timeline create a new layer called “Actions”. Select the first frame then hit F9 and enter the following code:

//1.change_btn.addEventListener(MouseEvent.CLICK, reverseMessage);

//2.function reverseMessage(event:MouseEvent):void {

var textInput:String = input_txt.text;

var inputArr:Array=textInput.split("");inputArr.reverse();

var reverseStr:String=inputArr.join("");output_txt.text = reverseStr;

}

Code:1. This is an event listener to the ‘change_btn’ with the mouse click event and the reverseMessage parameter.2. This is the reverseMessage function. The first line creates a new variable called ‘textInput’ which holds the data from when the user inputs text from the input box. The data from the input is then split into an array with an empty string as the delimiter. The reverse then is then called which reverses the order of the array. A new variable called ‘reverseStr’ is created which joins the reversed string together. Finally the reversed string is display in the output text box.

Step 6

Test your movie clip Ctrl + Enter. Now type some text and hit the reverse button and you should notice your text is reversed. Try reversing the following message: “enoyreve olleh” and leave a comment with the answer.