|
||||||
|
|
Chapter 10Strings, Math, and the History List
CONTENTS
Up to this point in the book, you have learned about the major objects and tools of JavaScript. Even so, this leaves several useful objects undiscovered. In this chapter you are going to take a detailed look at some of the objects that you have been introduced to only briefly earlier in the book. These include the string object, the Math object, and the history object. Every string in JavaScript is an object. The string object offers properties and methods to perform a variety of manipulations on a given string. These include methods for searching a string, extracting substrings, and applying HTML tags to the content of the string. The Math object provides those functions and methods necessary to perform mathematical calculations. These range from the PI value to methods for all the trigonometric functions. The history object is a bit different in that it doesn't involve the manipulation of information the way the string and Math objects do. The history object reflects the information in the browser's history list. In this chapter you will learn the details of each of these object's properties and methods plus:
The string ObjectYou already have considerable experience working with strings. You have used them throughout the book, you understand how to represent string literals, and you even know some of the basic techniques for examining the content of strings. Even with the substring() and indexOf() methods which you saw earlier, though, you haven't reached the true possibilities of working with the string object. The length PropertyThe string object has only one property: length. The length property is an integer value reflecting the number of characters in the string. Because the index of the first character in a string is zero, this means the length property is one greater than the index of the last character in the string. For example, the string "Hello" has a length of five. The index of the first character ("H") is 0, and the index of the last character ("o") is 4. Methods of the string Object
The flexibility and power of the string
object rest in the wide variety of methods available to manipulate
the content of the string. Table 10.1 outlines the methods available
in the string object.
The HTML MethodsAs you can see in Table 10.1, many of the methods of the string object are designed to add HTML tags to the content of the string so that when you display the string, it is suitably formatted. This can make the JavaScript code easier to read than if all the string assignments contained HTML tags, with the actual text to be displayed using document.write() or document.writeln(). The way these functions work is to return a new string containing the additional HTML tags. So, if you have a string variable named sample with the value "test", sample.big() returns "<BIG>test</BIG>" but sample still has a value of "test". For instance, the following JavaScript commands output the text "Hello!" in large, blinking, bold letters: var sample = "Hello!"; The following text displays the same word but as a hypertext link to the file: http://some.domain/some/file.html Because these methods return strings, you can also string together a series of methods and rewrite the first example as var sample = "Hello!"; To give you a better idea of what these methods actually do to the content of your strings, the script in Listing 10.1 displays the actual content of the strings using the XMP tag to force the browser not to interpret any HTML in the output.
Listing 10.1. Applying HTML tags with JavaScript's string object. <HTML>
The script produces results like those in Figure 10.1.
The second line of each pair calls the same method but this time without the surrounding XMP tags so that the user can see what the result looks like when treated as HTML. The substring() MethodYou have seen the substring() method several times in previous chapters. You first saw the substring() method in Exercise 6.3 when you used it to verify input in a form. To review, the method takes two integer arguments and returns the string starting at the first argument and ending at the character before the second argument. Where the first argument is larger, the process is reversed, and the substring starts at the second argument and continues until one character before the first argument. When both arguments are equal, an empty string is returned. For instance, if you have a string named sample with a value "Hello!", then sample.substring(0,3) is "Hel", sample.substring(3,0) is "Hel", and sample.substring(2,4) has the value "ll". The Case MethodsThe string object has two methods for changing the case of characters in a string. toLowerCase() returns a new string with all characters in lowercase. Similarly, toUpperCase() returns a copy of the string with all characters uppercase. For instance, if the variable sample is "tEsT", then sample.toLowerCase() is "test", and sample.toUpperCase() is "TEST". Using a combination of these methods and the substring() method, you can achieve more interesting results. If you want to take a string and make the first character uppercase and the rest lowercase, you could use the following technique: var sample = "tEsT"; Other MethodsThe string object has three other methods: indexOf(), lastIndexOf(), and charAt(). You saw the indexOf() method in Chapter 9, "Remember Where You've Been with Cookies." Simply, given two arguments (a string and an index) the method starts searching the string object from the index and looks for the first occurrence of the string that has been passed to it as an argument. It returns the index of this occurrence. This is best understood by example: If you have a string named sample with the value "Greetings! Welcome to Navigator 3.0! Enjoy!", then sample.indexOf("Wel",2) would return a value of 13 and sample.lastIndexOf("!",sample.length - 3) would return a value of 35. What happens in the first example is that the method starts searching the string sample from index 2 (the first "e" in "Greetings"). It checks if the phrase "Wel" starts at that index and if not, it moves to the next character (index 3) and tries again. This is repeated until the character at index 13, where a match is found. The send example is similar, but it moves backwards through the string looking for a match. In this case it starts at the 3 character from the end ("o" in "Enjoy") and moves back until it finds a "!". The other method, charAt(), is almost the reverse of this process. Given an index as an argument, it returns the character at that location. This is easier to use than the substring() method to extract a single character from a string. For instance, with the above string, both sample.charAt(3) and sample.substring(3,4) have the value of "e". With these methods, you can now develop tools to enable users to play with HTML to see how it looks. Using two frames, you will build an application that enables users to enter text in the left frame and select from a list of HTML attributes. They will see the text displayed with the combined attributes in the right frame, along with the actual HTML code needed to produce the results. Listings 10.2 through 10.4 contain the script files for the program. In order to do this, you need a top-level frameset which looks like Listing 10.2
. Listing 10.2. Top-level frameset. <HTML> The htmlform.html file is where all the work is done.
Listing 10.3. The htmlform.html file. <HTML> The file sample.html is just a blank HTML file to fill the window when the frame is initially loaded.
Listing 10.4. The source code for sample.html. <HTML>
This script produces results like those in Figure 10.2.
All the work is done in the file htmlform.html (Listing 10.3). The program only really does one task-displays information based on the content of a form-so only one function, display(), is necessary. function display(form) { You start by setting up the global variable format. You use this variable to hold the entire text and HTML tags to be tested. You start by assigning the content of the textarea input field, which contains the text you are going to test. You also define doc to be equal to the object parent.output. parent.output refers to the second frame in the frameset and is effectively the window object for that frame. In this way, you can use doc instead of parent.output. For instance, doc.document.write() is the same as parent.output.document.write(). format = (form.big.checked) ? format.big() : format; This section of code looks complex at first glance, but in reality, it is simple. You start by checking whether any of the checkboxes are checked. Because the checkbox object's checked property is a Boolean value, you can use it as the condition for a conditional expression, which performs the appropriate method and then assigns the result back to format. Next, you apply the appropriate fontcolor() and fontsize() methods based on the form content. If either field is empty, you use a default value. var result = "<CENTER>The HTML code: <XMP>"; The final task is to output the results. The string result holds the complete output for the second frame. Then you use document.open() to open a new output stream in the second frame for the HTML MIME type. You write the results to the frame and close the stream with document.close(). <FORM METHOD=POST>
The form is simple. When any text field changes, you call display()
and when any checkbox is clicked, you also call display().
No buttons are needed.
<SCRIPT LANGUAGE="JavaScript"> You end the body of the HTML file with a one-line script that calls display() for the first time to update the second frame with the contents of the form. This also could have been done in the onLoad event handler. Creating Search and Replace ToolsAnyone familiar with UNIX will miss many of the powerful text searching and matching tools found in the operating system and in scripting languages such as Perl, Awk, and sed. Although JavaScript provides the indexOf(), lastIndexOf(), charAt(), and substring() methods to help manipulate string contents, it doesn't provide powerful search and replace capabilities. In this example, you extend the functionality of JavaScript's text manipulation capabilities with simple search and replace functions. The search function should be able to search for words both in a case sensitive and case insensitive manner and should be able to search for whole words or substrings in words. Likewise, the replace function should be able to replace a word or substring, paying attention to case in the original text or ignoring it. The search function should return true or false, and the replace function should return a new string with the result of the replace. Listing 10.5 is the source code for these search and replace functions.
Listing 10.5. Searching and replacing in JavaScript. <SCRIPT LANGUAGE="JavaScript"> To demonstrate how these functions work, you can set up a simple search and replace application using the functions in Listing 10.6.
Listing 10.6. Using the search and replace functions. <HTML>
This script produces results like those in Figure 10.3.
Figure 10.3 : The search and replace functions can be used in any JavaScript application.
search() and replace() use a similar approach to handling their tasks, but differ in the specific actions they take when they find the term they are looking for. The replace() FunctionThe replace() function takes five arguments: the string to work on, the term to search for, the term to replace it with, and two Boolean values. The two Boolean values indicate whether to pay attention to the case of letters in searching and whether to search only for whole words (if not, substrings will be matched and replaced). var work = target; As would be expected, you start by setting up the work variables. if (!caseSens) { Then you check whether you are paying attention to case. If not, you change the search term and the string to search to lowercase, using the toLowerCase() method. This means that case is ignored in the searches because any variation in case in either string has been removed. while ((ind = work.indexOf(oldTerm,next)) >= 0) { All the work is done in the preceding while loop. In the condition of the while loop, you search the target string for the next occurrence of the search term, store the index in ind, and see if it is greater than zero. If you have found an occurrence of the term, you next check if you are searching for whole words or substrings. If you are searching for whole words, you use the space() function to check if the characters before and after the word boundary are word breaks. If they aren't, you update next to the index of the character after the term you just found and start the loop again. target = target.substring(0,ind) + newTerm + If you reach this point in the loop, then you have found a term you want to replace. You use the substring method to update both the string itself and change the variable next to the index of the character after the term you have just added. Finally, you check if you have reached the end of the target string, and if not, you run the loop again to look for another occurrence. The search() FunctionThis function is similar in structure to the replace() function. The differences lie in the while loop: while ((ind = target.indexOf(term,next)) >= 0) { As before, you perform the search for the search term using the indexOf() method in the condition of the while loop. Again, you check if you are searching for whole words, and if you are, you check for word boundaries. If you haven't found a complete word, you prepare to search again and return to the top of the loop with the continue statement. If you get beyond the if statements, you have found an occurrence of the term and return a true value from the function. If you finish the while loop without returning true, then you haven't found a match and you return a false value. The space() FunctionThe space() function plays a support role for search() and replace(). Given a character as an argument, the function checks whether it is one of a series of characters considered word breaks or delimiters. If it is, the function returns true-otherwise, it returns a false value. The way this is done is simple. All the possible word breaks are stored in the string space. A for loop goes through the string, character by character and compares each character to the argument. If there is a match, a true result is returned. After the loop, a comparison is made between the argument and either the empty string or the null value. If these are true, the function returns a true value as well. If you have failed all these conditions, then a false value is returned because the argument character is not a word break. If the programmer wants to change the definition of a word break, he or she simply has to change the declaration of the variable space. The Math ObjectWhere the string object enables you to work with text literals, the Math object provides methods and properties to move beyond the simple arithmetic manipulations offered by the arithmetic operators. Among the features offered by the Math object are several special values such as PI, natural logarithms, and common square roots, trigonometric methods, rounding methods, an absolute value method, and more.
Table 10.2 outlines all the properties and methods of the Math
object.
Some of these functions require further discussion. The Trigonometric MethodsYou will notice that the trigonometric methods, such as acos() and sin() use radians to measure the size of angles instead of the more familiar degrees. This isn't too difficult to handle. Where you have 360 degrees in a circle, there are 2¥PI (or roughly 6.283) radians in a circle. So, where the arc tangent of 1 is 45 degrees, in radians, the result is roughly 0.785398. The log() and exp() MethodsThe log() and exp() functions are related in that they use e, Euler's constant, as their base. The relationship between logarithms and exponential expressions is that if log(a) = b, then exp(b) = a. The abs() MethodThe absolute value method returns the positive value of a number. That is, it removes a negative sign from a number so that abs(4) and abs(-4) both have a value of 4. Calculating Geometric MeasurementsTo highlight some of these math functions, you are going to build a simple calculator that calculates the angles and the lengths of the sides of a right angle triangle and calculates the area, diameter, and circumference of a circle. In order to do this, you will use the trigonometric functions and PI. As a reminder, with a right angle triangle, if you want to calculate the sine, cosine, or tangent of any of the other two angles, you can use the following formulas: sine = opposite side / hypotenuse The script should be able to fill in all the information about the shapes when there is sufficient information in the relevant form. The results of Listing 10.7 look like Figure 10.4. Figure 10.4 : Using the Math object to perform more complex mathematical calculations.
Listing 10.7. Using the trigonometric functions. <HTML>
Figure 10.4 shows the result.
Figure 10.4 : Using the Math object to perform more complex mathematical calculations.
Of the two forms, the circle form is the simpler because it has less information to deal with. The following two sections analyze the two functions. The circle() FunctionThe circle() function takes two arguments: the form object and the name of the field that was just changed. The calculations are based on the name of this field. with (Math) {
You start by extracting whatever information is in the form and
storing it in local variables. Notice the use of the with
(Math) command. This enables all of the Math
properties and methods in the function to be used without the
Math prefix.
if (changed == "area") { The three if statement blocks simply calculate the other two fields based on the value of the changed field. All of these use two basic formulas: Area of Circle = PI¥radius¥radius Circumference of Circle = PI¥diameter Notice the use of the sqrt() method without the preceding Math prefix, which is made possible with the earlier with (Math) command. form.area.value = area; Once the calculation is done, you can reassign the results to the form. Working with the TriangleThe triangle function assumes that you are working with a right triangle. This means the angle across from the hypotenuse is always 90 degrees. The relationship between the remaining angles and sides is that sideA is adjacent to angleA and sideB is adjacent to angleB. Before you can proceed to calculate the information in this form, you need to be able to convert between degrees and radians. All the trigonometric functions either take a radian value as a parameter or return a radian value. Users, on the other hand, are likely to prefer working in degrees. You get around this by using the variables toDegrees and toRadians which represent the number of degrees per radian and the number of radians per degree: var toDegrees = 360 / (Math.PI * 2); The angle() function is called whenever you change one of the two angle values. It uses the fact that all the angles of a triangle add up to 180 degrees to calculate the remaining angle. Then, using the sin() and cos() methods and the formulas for sine and cosine, the program calculates the length of the opposite and adjacent sides for the changed angle. Finally, based on which angle was changed, the results are assigned to the correct form field. The side() function plays a similar role when either sideA or sideB is changed. Using the value of the changed side and the value of the hypotenuse, you can calculate the value of the third side using the formula: sideA¥sideA + sideB¥sideB = hypotenuse¥hypotenuse After you have the value for the three sides, you can use the acos() method and the formula for cosine to calculate the value of the two angles. The hypotenuse function simply calculates what the value of sideA and sideB should be based on the current angle settings by calling angle(form,"angleA"). You could just as easily have made the call angle(form,"angleB"). The forms in the body of the HTML file are fairly simple. They call the appropriate function in the onChange event handler for each text field. Working with the History ListWhen you use the Navigator browser, you will notice the history list, which is accessible under the Go menu. The history object makes this list accessible in JavaScript. Early versions of JavaScript made the actual URLs in the list available to the script, but this was too large a security hole because it could be used by malicious scripts to steal information to access some secure Web sites. In addition, it could be used to breach privacy by supplying a page author with information about what sites a visitor had previously visited. The history object provides methods for working with the list without actually reflecting the value of URLs and entries into a script. Properties and Methods of the history Object
Table 10.3 outlines the properties and methods available in the
history object.
For instance, history.back() goes to the previous page while history.go(-3) goes back to the page visited three pages ago (like clicking the Back button three times on the Navigator toolbar) and history.go(2) goes two URLs forward in the list. The history.go() method can also take a string instead of an integer as an argument. When a string is used, the method loads the nearest entry in the history that contains the string as part of its URL. The matching of the string against the URL is case insensitive. One of the more popular uses of the history object is to provide back and forward buttons in individual frames or dynamic back buttons, which take users back to the last page they were on. SummaryManipulating data has been the focus of much of this chapter. Using the string object, you now know how to add HTML tags using methods, how to change the case of a string, and how to search for the string and perform basic search and replace functions. The Math object enables you to extend the type of mathematical calculations you can perform to include trigonometry, logarithms, and square roots and also provides several values as properties, including PI, E, and LN2. The history object is a little different. By providing the ability to jump to URLs in the history list (without breaching security by providing the actual URL information), it is possible to build dynamic back and forward buttons into documents. In the next chapter you will put everything you have learned together into producing a fun cartoon face drawing program. Commands
and Extensions Review
|
Command/Extension | Type | Description |
anchor() | JavaScript method | Surrounds the string with an anchor A tag. |
big() | JavaScript method | Surrounds the string with the HTML BIG tag. |
blink() | JavaScript method | Surrounds the string with the HTML BLINK tag. |
bold() | JavaScript method | Surrounds the string with the HTML B tag. |
charAt() | JavaScript method | Given an index as an argument, returns the character at the specified index. |
fixed() | JavaScript method | Surrounds the string with the HTML TT tag to make it display as a fixed-width font. |
fontcolor() | JavaScript method | Surrounds the string with the HTML <FONT COLOR=color> and </FONT> tags to make it display in the specified color. |
fontsize() | JavaScript method | Surrounds the string with the HTML <FONT SIZE=size> and </FONT> tags to make it display in the desired font size. |
indexOf() | JavaScript method | Given a string and an initial index, returns the index of the next occurrence of the string after the initial index. |
italics() | JavaScript method | Surrounds the string with the HTML I tag. |
lastIndexOf() | JavaScript method | Given a string and a starting index, returns the index of the last occurrence of the string starting the search backward at the starting index. |
link() | JavaScript method | Given a URL, surrounds the string with an A tag to create a hypertext link |
small() | JavaScript method | Surrounds the string with the HTML SMALL tag. |
split() | JavaScript method | Returns an array by splitting a string at a specified separator. |
strike() | JavaScript method | Surrounds the string with the HTML STRIKE tag. |
sub() | JavaScript method | Surrounds the string with the HTML SUB tag. |
substring() | JavaScript method | Given two indexes, returns the substring starting at the first index and ending with the character before the last index. If the second index is greater, the substring starts with the second index and ends with the character before the first index; if the two indexes are equal, returns the empty string. |
sup() | JavaScript method | Surrounds the string with the HTML SUP tag. |
toLowerCase() | JavaScript method | Makes the entire string lowercase. |
toUpperCase() | JavaScript method | Makes the entire string uppercase. |
E | JavaScript property | Euler's constant-the base of natural logarithms (roughly 2.718). |
LN10 | JavaScript property | The natural logarithm of 10 (roughly 2.302). |
LN2 | JavaScript property | The natural logarithm of 2 (roughly 0.693). |
PI | JavaScript property | The ratio of the circumference of a circle to the diameter of the same circle (roughly 3.1415). |
SQRT1_2 | JavaScript property | The square root of 1/2 (roughly 0.707). |
SQRT2 | JavaScript property | The square root of 2 (roughly 1.414). |
abs() | JavaScript method | Calculates the absolute value of a number. |
acos() | JavaScript method | Calculates the arc cosine of a number-returns result in radians. |
asin() | JavaScript method | Calculates the arc sine of a number-returns result in radians. |
atan() | JavaScript method | Calculates the arc tangent of a number-returns result in radians. |
atan2() | JavaScript method | Calculates the angle of a polar coordinate based on a Cartesian coordinate. |
ceil() | JavaScript method | Returns the next integer greater than or equal to a number. |
cos() | JavaScript method | Calculates the cosine of a number. |
exp() | JavaScript method | Calculates e to the power of a number. |
floor() | JavaScript method | Returns the next integer less than or equal to a number. |
log() | JavaScript method | Calculates the natural logarithm of a number. |
max() | JavaScript method | Returns the greater of two numbers-takes two arguments. |
min() | JavaScript method | Returns the least of two numbers-takes two arguments. |
pow() | JavaScript method | Calculates the value of one number to the power of a second number-takes two arguments. |
random() | JavaScript method | Returns a random number between zero and one. |
round() | JavaScript method | Rounds a number to the nearest integer. |
sin() | JavaScript method | Calculates the sine of a number. |
sqrt() | JavaScript method | Calculates the square root of a number. |
tan() | JavaScript method | Calculates the tangent of a number. |
length | JavaScript method | The length of the history list. Also used in the string object to provide the value of the string. |
back() | JavaScript method | Loads the previous URL in the history list. |
forward() | JavaScript method | Loads the next URL in the history list. |
go() | JavaScript method | Loads the URL indicated by an offset from the current place in the history list. |
Use of this site is subject certain Terms & Conditions. Copyright (c) 1996-1999 EarthWeb, Inc.. All rights reserved. Reproduction in whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Please read our privacy policy for details. |