9.13. Reversing a String by Word or by Letter

Problem

You want to reverse a string either by word or by letter.

Solution

Use the split( ) method to create an array of the words/characters and use the reverse( ) and join( ) methods on that array.

Discussion

You can reverse a string by word or by character using the same process. The only difference is in the delimiter you use in the split( ) method and the joiner you use in the join( ) method. In either case, you should first split the string into an array—using a space as the delimiter for words or the empty string as the delimiter for characters. Then call the reverse( ) method of the array, which reverses the order of the elements. Finally, use the join( ) method to reconstruct the string. When reversing by word, use a space as the joiner, and when reversing by character, use the empty string as the joiner.

myString = "hello dear reader";

// Split the string into an array of words.
words = myString.split(" ");

// Reverse the array.
words.reverse(  );

// Join the elements of the array into a string using spaces.
myStringRevByWord = words.join(" ");

// Outputs: reader dear hello
trace(myStringRevByWord);

// Split the string into an array of characters.
chars = myString.split("");

// Reverse the array elements.
chars.reverse(  );

// Join the array elements into a string using the empty string.
myStringRevByChar = chars.join("");

// Outputs: redaer raed olleh
trace(myStringRevByChar);

Get Actionscript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.