9.8. Parsing a String into Words


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


Use the split( ) method.


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:

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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.