The primitive man wraps himself up in an animal skin to keep warm or to protect his skin. A primitive data type can also have a wrapper. The wrapper is an object bearing the same name as the data type it represents. For each of the primitive data types (string, number, and Boolean), there is a String object, a Number object, and a Boolean object. These objects are called wrappers and provide properties and methods that can be defined for the object. For example, the String object has a number of methods that let you change the font color , size, and style of a string; and the Number object has methods that allow you to format a number to a specified number of significant digits. Whether you use the object or literal notation to create a string, number, or Boolean, JavaScript handles the internal conversion between the types. The real advantage to the wrapper object is its ability to apply and extend properties and methods to the object, which in turn , will affect the primitive. 9.6.1 The String ObjectWe have used strings throughout this book. They were sent as arguments to the write() and writeln () methods, they have been assigned to variables , they have been concatenated , and so on. As you may recall, a string is a sequence of characters enclosed in either double or single quotes. The String object (starting with JavaScript 1.1) is a core JavaScript object that allows you to treat strings as objects. The String object is also called a wrapper object because it wraps itself around a string primitive, allowing you to apply a number of properties and methods to it. You can create a String object implicitly by assigning a quoted string of text to a variable, called a string primitive (see "Primitive Data Types" on page 31 of Chapter 3), or by explicitly creating a String object with the new keyword and the String() object constructor method. Either way, the properties and methods of the String object can be applied to the new string variable. FORMAT var string_name = "string of text"; var string_name = new String("string of text"); Example: var title="JavaScript by Example"; var title=new String("JavaScript by Example"); Example 9.19<html><head><title>The String Object</title></head> <body bgcolor=pink><font face="arial" size=+1> <h2>Primitive and String Objects</h2> <script language="JavaScript"> 1 var first_string = "The winds of war are blowing."; 2 var next_string = new String("There is peace in the valley."); 3 document.write("The first string is of type<em> "+ typeof(first_string) ); document.write(".</em><br>The second string is of type<em> "+ 4 typeof(next_string) +".<br>"); </script> </body> </html> EXPLANATION
The Properties of the String ObjectThe string properties (see Table 9.8) describe the attributes of the String object. The most common string property is the length property, which lets you know how many characters there are in a string. The prototype property allows you to add your own properties and methods to the String object, that is, you can customize a string. Table 9.8. String object properties.
Example 9.20<html><head><title>The String Object</title></head> <body bgColor="lightblue"> <font face="arial" size=+1> <h3>Length of Strings</h3> <script language="JavaScript"> 1 var first_string = "The winds of war are blowing."; var next_string = new String("There is peace in the valley."); 2 document.write("\""+first_string +"\" contains "+ first_string.length + " characters."); 3 document.write("<br>\""+ next_string+"\" contains "+ next_string.length +" characters.<br>"); document.write("<font size=-1><em>...not to imply that war is equal to peace...<br>"); </script> </body> </html> EXPLANATION
Example 9.21<html><head><title>The Prototype Property</title> <script language = "javascript"> // Customize String Functions 1 function ucLarge(){ var str=this.bold().fontcolor("white"). toUpperCase().fontsize("22"); return( str); } 2 String.prototype.ucL=ucLarge; </script> </head> <body bgcolor=black><center> <script language="JavaScript"> 3 var string="Watch Your Step!!"; 4 document.write( string.ucL() +"<br>"); </script> <img src="high_voltage.gif"> </body></html> EXPLANATION
String MethodsThere are two types of string methods: the string formatting methods that mimic the HTML tags they are named for, and the methods used to manipulate a string such as finding a position in a string, replacing a string with another string, making a string uppercase or lowercase, and the like. Table 9.9 lists methods that will affect the appearance of a String object by applying HTML tags to the string, for example, to change its font size, font type, and color. Using these methods is a convenient way to change the style of a string in a JavaScript program, much easier than using quoted HTML opening and closing tags. Table 9.9. String object (HTML) methods.
Example 9.22<html> <head><title>String object</title> </head> <body bgcolor="yellow"> <font size="+1" face="arial"> <h2>Working with String Objects:</h2> <script language="JavaScript"> 1 var str1 = new String("Hello world!"); // Use a String constructor 2 var str2 = "It's a beautiful day today."; document.write(str1) + "<br>"; 3 document.write( str1.fontcolor("blue" )+"<br>"); 4 document.write( str1.fontsize(8).fontcolor("red"). bold() +"<br>"); 5 document.write( str1.big() + "<br>"); 6 document.write(" Good-bye, ".italics().bold().big() + str2 + "<br>"); </script> </body></html> EXPLANATION
There are a number of methods (see Table 9.10) provided to manipulate a string. Table 9.10. Methods for string manipulation.
Methods That Find a Position in a StringA substring is a piece of an already existing string; thus eat is a substring of both create and upbeat , and java is a substring of javascript . When a user enters information, you want to see if a certain pattern of characters exist, such as the @ in an e-mail address or a zip code in an address. JavaScript provides a number of methods to assist you in finding substrings. The indexOf() and the lastIndexOf() methods are used to find the first instance or the last instance of a substring within a larger string. They are both case sensitive. The first character in a string is at index value 0, just like array indices. If either of the methods finds the substring, it returns the position of the first letter in the substring. If either method can't find the pattern in the string, then a “1 is returned. Example 9.23 <html><head><title>Substrings</title> </head> <body bgcolor=lightgreen> <font face="arial" size="+1"> Searching for an @ sign <script language="JavaScript"> 1 var email_addr=prompt("What is your email address? ",""); 2 while( email_addr.indexOf("@") == -1 ){ 3 alert( "Invalid email address."); email_addr=prompt("What is your email address? ",""); } document.write("<br>OK.<br>"); </script> </body></html> EXPLANATION
Example 9.24<html> <head><title>String Manipulation</title></head> </head> <body> <h2>Working with String Manipulation Methods</h2> <script language="JavaScript"> function break_tag(){ document.write("<br>"); } document.write("<h3>"); 1 var str1 = new String("The merry, merry month of June..."); document.write("In the string:<em> "+ str1 ); 2 document.write("</em> the first 'm' is at position " + str1.indexOf("m") ); break_tag(); 3 document.write("The last 'm' is at position " + str1.lastIndexOf("m") ); break_tag(); 4 document.write("<em>str1.substr(4,5)</em> returns<em> " + str1.substr(4,5) ); break_tag(); document.write (str1.toUpperCase() ); document.write("</h3>"); </script> </body> </html> Figure 9.26. Output from Example 9.24.
Methods that Extract Substrings from a StringYou may have to do more than just find a substring within a string, you may need to extract that substring. For example, we found the @ in the e-mail address, now we may want to get just the user name or the server name or domain name. To do this, JavaScript provides methods such as splice(), split(), charAt(), substr(), and substring() . Example 9.25<html><head><title>Extracting Substrings</title> </head> <body bgcolor=lightgreen> <font face="arial" size="+1"> Extracting substrings <font size="-1"> <script language="JavaScript"> 1 var straddr = "DanielSavage@dadserver.org"; document.write("<br>His name is<em> " + 2 straddr.substr(0,6) + "</em>.<br>"); 3 var namesarr = straddr.split("@" ); 4 document.write( "The user name is<em> " + namesarr[0] + "</em>.<br>"); 5 document.write( "and the mail server is<em> " + namesarr[1] + "</em>.<br>"); 6 document.write( "The first character in the string is <em>" + straddr.charAt(0) + "</em>.<br>"); 7 document.write( "and the last character in the string is <em>" + straddr.charAt(straddr.length - 1) + "</em>.<br>"); </script> </body></html> EXPLANATION
Search and Replace MethodsIn word processing software you'll always find some mechanism to search for patterns in strings and to replace one string with another. JavaScript provides methods to do the same thing, using the String object. The search() method searches for a substring and returns the position where the substring is found first. The match() method searches a string for substrings and returns an array containing all the matches it found. The replace() method searches for a substring and replaces it with a new string. These methods are discussed again in Chapter 13, "Regular Expressions and Pattern Matching," in more detail. Example 9.26<html><head><title>Search and Replace</title> </head> <body bgcolor=lightgreen> <font face="arial" size="+1"> Search and Replace Methods<br> <font size="-1"> <script language="JavaScript"> 1 var straddr = "DanielSavage@dadserver.org"; document.write( "The original string is "+ straddr + "<br>"); document.write( "The new string is "+ 2 straddr.replace("Daniel","Jake") +"<br>"); 3 var index=straddr.search("dad"); document.write("The search() method found \"dad\" at position "+ index +"<br>"); 4 var mysubstr=straddr.substr(index,3) ; document.write("After replacing \"dad\" with \"POP\" <br>"); 5 document.write( straddr.replace(mysubstr,"POP") +"<br>"); </script> </body></html> EXPLANATION
9.6.2 The Number ObjectNow that we've travelled this far in JavaScript, have you wondered how to format a floating-point number when you display it, as you can with the printf function in C or Perl? Well, the Number object, like the String object, gives you properties and methods to handle and customize numeric data. The Number object is a wrapper for the primitive numeric values (see Chapter 2, "Script Setup"), which means you can use a primitive number type or an object number type and JavaScript manages the conversion back and forth as necessary. The Number object was introduced in JavaScript 1.1. The Number() constructor takes a numeric value as its argument. If used as a function, without the new operator, the argument is converted to a primitive numeric value, and that number is returned; if it fails, NaN is returned. The Number object has a number of properties and methods, as listed in Tables 9.11 and 9.12. FORMAT var number = new Number(numeric value); var number = Number(numeric value); Example: var n = new Number(65.7); Table 9.11. The Number object's properties.
Table 9.12. The Number object's methods.
Using Number Constants and Different BasesThe constants MAX_VALUE, MIN_VALUE, NEGATIVE_INFINITY, POSITIVE_INFINITY , and NaN , are properties of the Number() function, but are not used with instances of the Number object; thus, var huge = Number.MAX_VALUE is valid, but huge.MAX_VALUE is not. NaN is a special value that is returned when some mathematical operation results in a value that is not a number. The methods provided to the Number object manipulate instances of number objects. For example, to convert numbers to strings representing different bases, the toString() method manipulates a number, either primitive or object. See Example 9.27. Example 9.27<html> <head><title>Number Contants</title> </head> <body bgcolor=orange><font color="black" size="+1"> <h2> Constants </h2> <script language="JavaScript"> 1 var largest = Number.MAX_VALUE; 2 var smallest = Number.MIN_VALUE; 3 var num1 = 20; // A primitive numeric value 4 var num2 = new Number(13); // Creating a Number object document.write("<b>The largest number is " + largest + "<br>"); document.write("The smallest number is "+ smallest + "<br>"); 5 document.write("The number as a string (base 2): "+ num1.toString(2) ); 6 document.write("<br>The number as a string (base 8): "+ num2.toString(8) ); 7 document.write("<br>The square root of -25 is: "+ Math.sqrt(-25) + "<br>"); </script> </body> </html> EXPLANATION
Formatting NumbersTo convert floating-point numbers to a string with a specified number of significant digits, JavaScript provides the toFixed() and toExponential() methods. Example 9.28<html> <head><title>Number Object</title> </head> <body bgcolor=orange><font color="black" size="+1"> <h2> Formatting Numbers </h2> <script language="JavaScript"> 1 var n = new Number(22.425456); 2 document.write("<b>The unformatted number is " + n + "<br>"); 3 document.write("The formatted number is "+ n.toFixed(2) + "<br>"); 4 document.write("The formatted number is "+ n.toFixed(3) + "<br>"); </script> </body> </html> EXPLANATION
9.6.3 The Boolean ObjectThe Boolean object was included in JavaScript 1.1. It is used to convert a non-Boolean value to a Boolean value, either true or false . There is one property, the prototype property, and one method, the toString() method, which converts a Boolean value to a string; thus, true is converted to "true" and false is converted to "false" . FORMAT var object = new Boolean(value); Example: var b1 = new Boolean(5); var b2 = new Boolean(null); Example 9.29<html><head><title>Boolean Object</title> </head> <body bgcolor=aqua> <font face="arial" size="+1"><b> The Boolean Object<br> <font size="-1"> <script language="JavaScript"> 1 var bool1= new Boolean( 0); var bool2 = new Boolean(1); var bool3 = new Boolean(""); var bool4 = new Boolean(null); var bool5 = new Boolean(NaN); 2 document.write("The value 0 is boolean "+ bool1 +"<br>"); document.write("The value 1 is boolean "+ bool2 +"<br>"); document.write("The value of the empty string is boolean "+ bool3+ "<br>"); document.write("The value of null is boolean "+ bool4+ "<br>"); document.write("The value of NaN is boolean "+ bool5 +"<br>"); </script> </body></html> EXPLANATION
9.6.4 The Function ObjectThe Function object (added in JavaScript 1.1) lets you define a function as an object dynamically. It allows a string to be defined at runtime and then compiled as a function. You can use the Function() constructor to create a variable that contains the function. Since the function has no name, it is often called an anonymous function and its arguments are passed as comma-separated strings. The last argument is the body of statements that will be executed when the function is called. If the Function() constructor does not require arguments, then the body of statements, treated as a string, will be passed to the Function() constructor to define what the function is to do. Since functions are objects, they also have properties (see Table 9.13) and methods (see Table 9.14). Function objects are evaluated each time they are used, causing them to be slower in execution than normal JavaScript functions. Table 9.13. Properties of the Function object.
Table 9.14. Methods of the Function object.
FORMAT var nameOfFunction = new Function (arguments, statements_as_string: } Example Function Definition: var addemUp = new Function ( "a", "b", "return a + b;" ); Example Function Call: document.write(addemUp (10, 5)); Example 9.30<html><head><title>Function Object</title> </head> <body bgcolor=lightgreen> <font face="arial" size="+1"> <center> Anonymous Functions and the Function Constructor<p> <script language="JavaScript"> 1 var sum = new Function("a","b", "return a + b; "); 2 window.onload = new Function ( "document.bgColor='yellow';"); 3 document.write( "The sum is " + sum(5,10) + "<br>"); document.write( "The background color is yellow<br>"); </script> </body></html> EXPLANATION
9.6.5 The with Keyword RevisitedIn Chapter 8, we used the with keyword with user-defined objects to make it easier to manipulate the object properties. Recall that any time you reference the object within the block following the keyword, you can use properties and methods without the object name. This saves a lot of typing and reduces the chances of spelling errors, especially when the properties have long names . The String object is used in the following example to demonstrate how with is used. Example 9.31<html><head><title>The with Keyword</title> </head> <body> <h2>Using the <em>with</em> keyword</h2> <p> <h3> <script language="JavaScript"> var yourname =prompt("What is your name? ",""); // Create a string object with(yourname){ document.write("Welcome " + yourname + " to our planet!!<br>"); document.write("Your name is " + length + " characters in length.<br>"); document.write("Your name in uppercase: " + toUpperCase() + ".<br>"); document.write("Your name in lowercase: " + toLowerCase() + ".<br>"); } </script> </h3> </body></html> Figure 9.33. Using the with keyword to reference an object.
|