Getting Playful with Strings


In this section, we’re going to get down, get funky, and have some fun with strings. The example program in this section has functions that do the following:

  • Capitalize all the “words” in a string.

  • Count the “words” in a string.

  • Reverse the “words” in a string.

  • Reverse the string itself.

In order to set up a user interface for this, our program will provide two HTML <textarea> elements: one for the user to input a string, the other to display the results of the string manipulation (see Figure 9-3).

click to expand
Figure 9-3: The Playing with Strings user interface is shown with the words in a string capitalized.

Besides the <textarea> elements for the input of a string and the display of the manipulated string, the user interface provides five buttons. Four of the buttons will activate one of the functions listed previously, and the fifth button will be used to clear the user’s input string.

These buttons are also shown in Figure 9-3. The onClick event associated with each of these buttons activates the corresponding functionality.

Listing 9-3 shows the HTML used to create this user interface, along with the onClick event handler for each button. (I’ve omitted the <TABLE> tags for clarity—to see them, check out the complete code shown in Listing 9-7.)

Listing 9.3: The HTML User Interface for the Playing with Strings Application (Including onClick Event Handlers)

start example
 <BODY> <H1>  Playing with strings!  </H1> <FORM name="theForm">  Enter a text string:  <TEXTAREA name=inStr rows=5 cols=90> </TEXTAREA> <INPUT type=button value="Capitalize Words"     onClick="capWords(document.theForm.inStr.value)";> <INPUT type=button value="Count Words"     onClick="countWords(document.theForm.inStr.value)";> <INPUT type=button value="Reverse Words"     onClick="revWords(document.theForm.inStr.value)";> <INPUT type=button value="Reverse String"     onClick="document.theForm.results.value =  revString(document.theForm.inStr.value)";> <INPUT type=button value="Clear"  onClick='document.theForm.inStr.value=""';>  Results  <TEXTAREA name=results rows=5 cols=90> </TEXTAREA> <INPUT type=button name="theButton" value="Clear Results"     onClick='document.theForm.results.value=""';> </FORM> </BODY> 
end example

Listing 9.7: Playing with Strings

start example
 <HTML> <HEAD> <TITLE>String Play</TITLE> <SCRIPT>  function capWords(str){     // break into an array of words,     // using space as the delimiter     var words = str.split(" ");     for (var i=0 ; i < words.length ; i++){        // inner loop -- do the capitalizing        var testwd = words[i];        var firLet = testwd.substr(0,1); //lop off first letter        var rest = testwd.substr(1, testwd.length -1)        words[i] = firLet.toUpperCase() + rest     }     document.theForm.results.value = words.join(" ");  }  function countWords(str){     var count = 0;     // break into an array of words,     // using space as the delimiter     // words.length won't work because of spaces    var words = str.split(" ");      for (i=0 ; i < words.length ; i++){         // inner loop -- do the count         if (words[i] != "")            count += 1;      }     document.theForm.results.value =        "There are " +        count +        " words in the text string you entered!";  }  function revWords(str){     // break into an array of words,     // using space as the delimiter     var words = str.split(" ");     var j = words.length - 1;     var backWords = new Array();     for (i=0 ; i < words.length ; i++){        backWords[j] = words[i];        j-    }     document.theForm.results.value = backWords.join(" ");  }  function revString(str) {     var retStr = "";     for (i=str.length - 1 ; i > - 1 ; i--){        retStr += str.substr(i,1);     }     return retStr;  }  </SCRIPT> </HEAD> <BODY> <H1>  Playing with strings!  </H1> <FORM name="theForm"> <TABLE> <tr> <td colspan=5>  Enter a text string:  </td> </tr> <tr> <td colspan=5> <TEXTAREA name=inStr rows=5 cols=90> </TEXTAREA> </td> </tr> <tr> <td> <INPUT type=button value="Capitalize Words"     onClick="capWords(document.theForm.inStr.value)";> </td> <td> <INPUT type=button value="Count Words"  onClick="countWords(document.theForm.inStr.value)";> </td> <td> <INPUT type=button value="Reverse Words"     onClick="revWords(document.theForm.inStr.value)";> </td> <td> <INPUT type=button value="Reverse String"     onClick="document.theForm.results.value =  revString(document.theForm.inStr.value)";> </td> <td> <INPUT type=button value="Clear"  onClick='document.theForm.inStr.value=""';> </td> </tr> <tr> <td colspan=5> <br> <hr>  Results<br> </td> </tr> <tr> <td colspan=5> <TEXTAREA name=results rows=5 cols=90> </TEXTAREA> </td> </tr> <tr> <td colspan=5> <INPUT type=button name="theButton" value="Clear Results"     onClick='document.theForm.results.value=""';> </td> </tr> </TABLE> </FORM> </BODY> </HTML> 
end example

Splitting a String

Let’s not split hairs—instead, let’s split strings!

The functions I’m about to show you that do things to the “words” in a string use the split method of the String object.

No, the split method isn’t something devised to break up couples! Rather, the split method breaks a string into an array of strings, using a specified delimiter. The delimiter is a character or string that’s used to specify where the original string splits. For example, if you had the string "Ohana means family", and the delimiter were the string " means ", then using the split method would create a two-element array with the first element containing the value "Ohana" and the second element containing the value "family".

Here’s the way this little example might look in code:

 var str = "Ohana means family";  var delim =" means ";  var strArray = new Array(str.split(delim)); 

strArray[0] would now contain the string value "Ohana" and strArray[1] would contain the value "family".

Advanced Note

You can also use a regular expression as the delimiter. Regular expressions are explained in the “ Regular Expressions ” section of this chapter.

A crude way to separate the words out of a string of text is to split the string using the space character (" ") as the delimiter. The examples in this section use this recipe, which isn’t perfect! There are a number of special situations that cause it to not capitalize words that should be capitalized. For example, a word immediately following a quotation will not be capitalized. Another example: A word entered following a line break will not be capitalized unless spaces were also entered.

Certainly, you could write code to deal with each special case that mattered to you. As a matter of fact, as an exercise, why don’t you write some code to deal with each of these special situations? (Hint: The easiest thing to do to cover several cases is to use a regular expression as the delimiter.)

In the meantime, close enough is good enough! The examples in this section will use a space character (" ") as a crude way to split text strings into words. But let’s just be sure that we’re on the same page that this isn’t a perfect way to determine the words in a text string.

Capitalizing “Words” in a String

Listing 9-4 shows the capWords function that capitalizes the first letter in each word of the string. The function also assigns its results to the value of the results <textarea> element, but alternatively you could design the function to just return a value (the string with the first letter of each word capitalized).

Listing 9.4: Capitalizing the First Letter in Each Word of a String

start example
 function capWords(str){     var words = str.split(" ");     for (var i=0 ; i < words.length ; i++){        var testwd = words[i];        var firLet = testwd.substr(0,1);        var rest = testwd.substr(1, testwd.length -1)        words[i] = firLet.toUpperCase() + rest     }     document.theForm.results.value = words.join(" ");  } 
end example

If you open the page containing the user interface HTML and the capWords function in a browser, you can enter text as shown in Figure 9-3.

When you click Capitalize Words, the button’s onClick handler calls the capWords function, which displays the results of capitalizing the first letters of each word in the results <textarea>, also as shown in Figure 9-3.

Here’s how the capWords function works:

  1. The input string is broken up into an array of words using a space as a delimiter.

  2. The array of words is iterated through.

  3. Each “word” is divided into two strings using the String object’s substr method.

  4. The two strings are the first letter and the rest of the word.

  5. The first letter is capitalized using the toUpperCase method.

  6. The capitalized first letter is concatenated back together with the rest of the word.

  7. The remade word is assigned as the value in the array of words.

  8. The array of words is joined together, with a space character inserted between each element.

  9. The result is assigned to the value of the <textarea> (alternatively, this value could be used as the return value of the function).

Counting “Words”

Listing 9-5 shows the function used to count the words in a text string.

Listing 9.5: Counting the Words in a Text String

start example
 function countWords(str){     var count = 0;     var words = str.split(" ");      for (i=0 ; i < words.length ; i++){         // inner loop -- do the count         if (words[i] != "")            count += 1;      }     document.theForm.results.value =        "There are " +        count +        " words in the text string you entered!";  } 
end example

As with the example in the previous section that capitalizes the first letter of each word, the split method is used to save each word as an element of an array.

If you’re looking at this code carefully, you might wonder at this point why we can’t just assume that the length property of the array of words is the number of words in the array. However, the length property of the words array can’t be used by itself to determine the number of words because some of the elements of the array may be strings without characters (spaces). It’s necessary to include a test for empty words:

 if (words[i] != "")      count += 1; 

As an exercise, it might be fun to see what happens without this test. Rewrite the code to simply return the length of the words array and try entering a string with multiple spaces between words. You’ll find the count is inaccurate. What other ways of rewriting this code can you think of?

If you run the code in the user interface in a Web browser, enter a text string containing words, and click Count Words, the number of words in the string will be displayed (see Figure 9-4).

click to expand
Figure 9-4: The function counts the number of words in a string.

Reversing the Words in a String

We’ll take a slightly different tack to reverse the words in a string.

Here’s how the process will work conceptually:

  1. First, the input string is broken up into an array of words using the split method in the usual fashion.

  2. A new array, backwards, is created to hold the words in backwards order.

  3. As the original array is looped through, each word is assigned to the backwards array. However, the backwards array uses a counter that starts at the top and works its way down.

  4. Finally, the elements of the backwards array are joined together and displayed as the results of the operation.

The following shows the process with the actual code that will be used.

To Reverse the Words in a String:.

  1. Split the string into an array of words, using a space as the delimiter:

     function revWords(str){     var words = str.split(" ");  } 

  2. Create a new array for the reversed string:

     function revWords(str){     var words = str.split(" ");     var backWords = new Array();  } 

  3. Assign the last word of the old array to the first element of the new array. In other words, cycle backwards through the original array:

     function revWords(str){     var words = str.split(" ");     var j = words.length - 1;     var backWords = new Array();     for (i=0 ; i < words.length ; i++){        backWords[j] = words[i];        j-    }  } 

  4. Display the results:

     function revWords(str){     var words = str.split(" ");     var j = words.length - 1;     var backWords = new Array();     for (i=0 ; i < words.length ; i++){        backWords[j] = words[i];        j-    }     document.theForm.results.value = backWords.join(" ");  } 

  5. Add the function to the user interface and open the page in a Web browser.

  6. Enter some text containing words in the upper textarea box.

  7. Click Reverse Words. The reversed words will be displayed in the bottom textarea box (see Figure 9-5).

    click to expand
    Figure 9-5: The words in the text string are reversed.

Reversing a String

Reversing a string is a pretty common programming task. In fact, many programming languages (but not JavaScript) have a built-in string method for reversing a string.

I’m sure you’ll appreciate that reversing a string is a different operation from reversing the order of the words in a string.

The string reversal function I’ll show you, revString, shown in Listing 9-6, returns the reversed string value rather than displaying the value, so it’s a more generally usable function.

Listing 9.6: Reversing a String

start example
 function revString(str) {     var retStr = "";     for (i=str.length - 1 ; i > - 1 ; i--){        retStr += str.substr(i,1);     }     return retStr;  }  ...  <INPUT type=button value="Reverse String"     onClick="document.theForm.results.value =  revString(document.theForm.inStr.value)";> 
end example

The idea is to iterate through the string input from the top, or last, character down. Each character is then added to the beginning of the new, reversed string using the substr method.

Tip

Remember that being “one off” is a great source of programming errors! Think carefully about the upper and lower bounds for loops such as the one used in Listing 9-6 because it’s easy to be off by one.

The revString function is called and passed the input value in one fell swoop in an assignment statement in the onClick handler (as shown at the end of Listing 9-6).

If you run the function within the user interface opened in a browser, you can enter a text string. Next, click the Reverse String button. The reversed string will appear in the bottom textarea box (see Figure 9-6).

click to expand
Figure 9-6: The string has been reversed.

You can go ahead and play with these strings, using more than one of the string manipulation functions on a given string by copying and pasting the results of an initial manipulation back into the upper box and then applying another manipulation function.

For example, Figure 9-7 shows the reversed string created in Figure 9-6 but with all the first letters of words capitalized.

click to expand
Figure 9-7: The first letters of the words in the reversed string have been capitalized.

Listing 9-7 shows the complete code for the Playing with Strings application.




Learn How to Program Using Any Web Browser
Learn How to Program Using Any Web Browser
ISBN: 1590591135
EAN: 2147483647
Year: 2006
Pages: 115
Authors: Harold Davis

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net