DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 9.13 Reversing a String by Word or by Letter

9.13.1 Problem

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

9.13.2 Solution

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

9.13.3 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);
    [ Team LiB ] Previous Section Next Section