9.6 What Is a Wrapper Object?

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 Object

We 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.


 var string_name = "string of text"; var string_name = new String("string of text"); 


 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> 


  1. This is the literal way to assign a string to a variable, and the most typical way. The string is called a string primitive. It is one of the basic building blocks of the language, along with numbers and Booleans. All of the properties and methods of the String object behave the same way whether you create a String literal or a String object as shown next . For all practical purposes, both methods of creating a string are the same, though this one is the easiest .

  2. The String() constructor and the new keyword are used to create a String object. This is the explicit way of creating a string.

  3. The typeof operator demonstrates that the first string, created the literal, implicit way, is a String data type.

  4. The typeof operator demonstrates that this string, created with the String() constructor, is an object type. Either way, when properties and methods are applied to a string, it is treated as a String object. (See Figure 9.20.)

    Figure 9.20. Output from Example 9.19.


The Properties of the String Object

The 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.


What It Does


Returns the length of the string in characters


Extends the definition of the string by adding properties and methods

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> 


  1. Two strings are created, one the literal way (a string primitive) and the other with the constructor method (a String object).

  2. The length property is applied to the first string. When the property is applied to a literal string, it is temporarily converted to an object, and then after the operation, it is reverted back to a string primitive.

  3. The length property is applied to the second string, a String object. (It is just a coincidence that both strings are of the same length.) (See Figure 9.21.)

    Figure 9.21. Using the String object's length property. Output from Example 9.20.


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> 


  1. The ucLarge() function is defined. Its purpose is to generate and return an uppercase, bold, white font, with a point size of 22.

  2. The prototype property allows you to customize an object by adding new properties and methods. The name of the customized method is ucL , which is the name of a new method that will be used by the String object. It is assigned the name (without parentheses) of the function ucLarge() , that performs the method's actions and returns a value.

  3. A new string is created.

  4. The prototyped method, ucL() , is applied to the String object, str . It will modify the string as shown in the output in Figure 9.22.

    Figure 9.22. Using the String object's prototype property. Output from Example 9.21.


String Methods

There 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.


Formats as HTML


<a name="Name">String</a>










<font color="color">String</font>

e.g., <font color="blue">String</font>


<font size="size">String</font>

e.g., <font size="+2">String</font>



String.link( URL )

<a href=" URL ">String</a>

e.g., <a href="http://www.ellieq.com">String</a>




<strike>String</strike> (puts a line through the text)


<sub>String</sub> (creates a subscript)


<sup>String</sup> (creates a superscript)

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> 


1 A String object is created with the String() constructor.

2 A string primitive is created the literal way.

3 The fontcolor() method is used to change the color of the string to blue. This method emulates the HTML tag, < font color="blue">.

4 The fontsize(), fontcolor() , and bold() methods are used as properties of the string.

5, 6 The HTML method is concatenated to the string "Good-bye, " causing it to be displayed in italic, bold, big text. (See Figure 9.23.)

Figure 9.23. Properties of the String object are used to change its appearance and determine its size. Output from Example 9.22.


There are a number of methods (see Table 9.10) provided to manipulate a string.

Table 9.10. Methods for string manipulation.


What it Does


Returns the character at a specified index position


Returns the Unicode encoding of the character at a specified index position

concat(string1, ..., stringn)

Concatenates string arguments to the string on which the method was invoked


Creates a string from a comma-separated sequence of character codes

indexOf(substr, startpos)

Searches for first occurrence of substr starting at startpos and returns the startpos(index value) of substr

lastIndexOf(substr, startpos)

Searches for last occurrence of substr starting at startpos and returns the startpos (index value) of substr

replace(searchValue, replaceValue)

Replaces searchValue with replaceValue


Searches for the regular expression and returns the index of where it was found

slice(startpos, endpos)

Returns string containing the part of the string from startpos to endpos

split( delimiter )

Splits a string into an array of words based on delimiter

substr(startpos, endpos)

Returns a subset of string starting at startpos up to, but not including, endpos


Returns a copy of the string converted to lowercase


Returns a copy of the string converted to uppercase


Converts all characters in a string to lowercase letters


Returns the same string as the source string


Converts all characters in a string to uppercase letters


Returns the string value of the object

Methods That Find a Position in a String

A 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> 


  1. The user is prompted for his e-mail address and the input is assigned to a string called email_addr .

  2. The loop expression uses the indexOf() String method to see if there is an @ symbol in the e-mail address. If there isn't, the indexOf() method returns “1 and the body of the loop is executed.

  3. If the indexOf() method didn't find the @ substring, the alert box appears and the user is prompted again (see Figures 9.24 and 9.25). The loop terminates when the user enters an e-mail address containing an @ sign. Of course, this is just a simple test for validating an e-mail address; more elaborate methods of validation are discussed in Chapter 13, "Regular Expressions and Pattern Matching."

    Figure 9.24. Using the indexOf() String method.


    Figure 9.25. The user entered an e-mail address without the @ symbol.


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 String

You 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> 


  1. A string is assigned an e-mail address.

  2. The substr() starts at the first character at position 0, and yanks 6 characters from the starting position. The substring is Daniel .

  3. The split() method creates an array, called namesarr , by splitting up a string into substrings based on some delimiter that marks where the string is split. This string is split using the @ sign as its delimiter.

  4. The first element of the array, namesarr[0] , that is created by the split() method is DanielSavage , the user name portion of the e-mail address.

  5. The second element of the array, namesarr[1] , that is created by the split() method is dadserver.org , the mail server and domain portion of the e-mail address.

  6. The charAt() method returns the character found at a specified position within a string; in this example, position 0. Position 0 is the first character in the string, a letter D .

  7. By giving the charAt() method the length of the string minus 1, the last character in the string is extracted, a letter g . (See Figure 9.27.)

    Figure 9.27. The charAt(), split() , and substr() methods. Output from Example 9.25.


Search and Replace Methods

In 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> 


  1. An e-mail address is assigned to the string variable straddr .

  2. The replace() method takes two arguments, the search string and the replacement string. If the substring Daniel is found, it is replaced with Jake .

  3. The search() method takes a subtring as its argument and returns the first position where a substring is found in a string. In this example the substring dad is searched for in the string DanielSavage@dadserver.org and is found at position 13.

  4. The substr() method returns the substring found at position 13, 3 in the string, DanielSavage@dadserver.org : dad.

  5. The substring dad is replaced with POP in the string. (See Figure 9.28.)

    Figure 9.28. The search() and replace() String methods. Output from Example 9.26.


9.6.2 The Number Object

Now 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.


 var number = new Number(numeric value); var number = Number(numeric value); 


 var n = new Number(65.7); 
Table 9.11. The Number object's properties.


What It Describes


The largest representable number, 1.7976931348623157e+308


The smallest representable number, 5e “324


Not-a-number value


Negative infinite value; returned on overflow


Infinite value; returned on overflow


Used to customize the Number object by adding new properties and methods

Table 9.12. The Number object's methods.


What It Does


Converts a number to a string using a specified base (radix)


Converts a number to a string using local number conventions

toFixed() [1]

Converts a number to a string with a specified number of places after the decimal point


Converts a number to a string using exponential notation and a specified number of places after the decimal point


Converts a number to a string in either exponential or fixed notation containing the specified number of places after the decimal point

[1] These methods are part of the ECMA 3.0, IE5.5+, Netscape 6.0+.

Using Number Constants and Different Bases

The 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> 


  1. The constant MAX_VALUE is a property of the Number() function. This constant cannot be used with an instance of a Number object.

  2. The constant MIN_VALUE is a property of the Number() function.

  3. A number is assigned to the variable called num1 .

  4. A new Number object is created with the Number() constructor and assigned to num2 .

  5. The number is converted to a string represented in binary, base 2.

  6. The number is converted to a string represented in octal, base 8.

  7. The square root of a negative number is illegal. JavaScript returns NaN , not a number, when this calculation is attempted. (See Figure 9.29.)

    Figure 9.29. Constants, number conversion, and NaN . Output from Example 9.27.


Formatting Numbers

To 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> 


  1. A new Number object is created and assigned to the variable n .

  2. The value of the number is displayed as a large floating-point number, 22.425456.

  3. The Number object's toFixed() method gets an argument of 2. This fixes the decimal point two places to the right of the decimal point and rounds up if necessary. The new value is 22.43.

  4. This time the toFixed() method will format the number with three numbers to the right of the decimal point. (See Figure 9.30.)

    Figure 9.30. Using the toFixed() Number method. Output from Example 9.28.


9.6.3 The Boolean Object

The 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" .


 var object = new Boolean(value); 


 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> 


  1. The argument passed to the Boolean object constructor is the initial value of the object, either true or false . If the initial value is , the empty string "", NaN , or null , the result is false ; otherwise , the result is true .

  2. The Boolean object's values are displayed as either true or false . (See Figure 9.31.)

    Figure 9.31. True or False ? Output from Example 9.29.


9.6.4 The Function Object

The 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.


What It Does


Returns the number of arguments that are expected to be passed (read only)


Allows the object to be customized by adding new properties and methods

Table 9.14. Methods of the Function object.


What It Does

apply() [*]

Allows you to apply a method from one function to another


Allows you to call a method from another object

[*] Supported on versions Netscape 4.06+ and Internet Explorer 5.5+.


 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> 


  1. A variable called sum is a Function object, created by the Function() constructor. It has two arguments, "a" and "b" . The function statements are the last string in the list. These statements will be executed when the function is called.

  2. This Function() constructor only has one argument, the statement that will be executed when the function is called. Since the function is assigned to the onload event method for the window object, it will act as an event handler and cause the background color to be yellow when the document has finished loading.

  3. The sum function is called with two arguments. (See Figure 9.32.)

    Figure 9.32. Output from Example 9.30.


9.6.5 The with Keyword Revisited

In 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.


JavaScript by Example
JavaScript by Example (2nd Edition)
ISBN: 0137054890
EAN: 2147483647
Year: 2003
Pages: 150
Authors: Ellie Quigley

Similar book on Amazon

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