Java Reference
In-Depth Information
Figure 9-2
Try changing the lines within the text area to test it further.
Although this example works on Internet Explorer (IE) as it is, an extra line gets inserted. If this troubles
you, you can fi x it by replacing each instance of \n with \r\n for IE.
The key to how this code works is the function splitAndReverseText(). This function is defi ned in
the script block in the head of the page and is connected to the onclick event handler of the button
further down the page.
<input type=”button” value=”Reverse Line Order” name=buttonSplit
onclick=”splitAndReverseText(document.form1.textarea1)”>
As you can see, you pass a reference of the text area that you want to reverse as a parameter to the func-
tion. By doing it this way, rather than just using a reference to the element itself inside the function, you
make the function more generic, so you can use it with any textarea element.
Now, on with the function. You start by assigning the value of the text inside the textarea element to
the textToSplit variable. You then split that string into an array of lines of text using the split()
method of the String object and put the resulting array inside the textArray variable.
function splitAndReverseText(textAreaControl)
{
var textToSplit = textAreaControl.value;
var textArray = textToSplit.split('\n');
So what do you use as the separator to pass as a parameter for the split() method? Recall from
Chapter 2 that the escape character \n is used for a new line. Another point to add to the confusion is
that IE seems to need \r\n rather than \n .
You next defi ne and initialize three more variables.
var numberOfParts = 0;
numberOfParts = textArray.length;
var reversedString = “”;
var indexCount;
Now that you have your array of strings, you next want to reverse them. You do this by building up a
new string, adding each string from the array, starting with the last and working toward the fi rst. You
Search WWH ::




Custom Search