9.8. Parsing a String into Words

Problem

You want to process a string one word at a time.

Solution

Use the split( ) method.

Discussion

The split( ) method (see Recipe 6.6) splits a string into an array using the specified delimiter. To split a string into separate words, use the split( ) method with a space as the delimiter:

// Create a string with multiple words.
myString = "this is a string of words";

// Split the string into an array of words using a space as the delimiter.
words = myString.split(" ");

// Loop through the array and do something with each word. In this example, we just
// output the values.
for (var i = 0; i < words.length; i++) {
  /* Displays:
     this
     is
     a
     string
     of
     words
  */
  trace(words[i]);
}

You can process the individual words in many ways. Here is an example that uses this technique to split a string into words and then creates movie clips containing those words. The user can then drag the words around on stage to form various sentences or statements, as in the popular magnetic poetry kits.

// Create a string and split the string into an array of words. myString = "This is a string of ActionScript poetry words"; words = myString.split(" "); // Loop through all the words in the array. for (var i = 0; i < words.length; i++) { // Create a new movie clip for each word. word_mc = _root.createEmptyMovieClip("word" + i, i); // Create a text field within each movie clip. word_mc.createTextField("word_txt", 1, 0, 0, 0, 0); // The text field should autosize to fit its contents. ...

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.