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 numb
Trang 1provide 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.5.4 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
concate-nated, and so on As you might 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
vari-able, called a string primitive (see “Primitive Data Types” on page 53 of Chapter 3, “The
Building Blocks: Data Types, Literals, and Variables”), 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.
Figure 9.26 Producing random numbers (Example 9.22).
Trang 2F O RM A T
var string_name = "string of text";
var string_name = new String("string of text");
E X A M P L E
var title="JavaScript by Example";
var title=new String("JavaScript by Example");
E X A M P L E 9 2 3
<html>
<head><title>The String Object</title></head>
<body bgcolor="pink">
<font face="arial">
<big>
<h2>Primitive and String Objects</h2>
<script type="text/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> "
</script>
</big>
</font>
</body>
</html>
E X P L A N A T I O N
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
lan-guage, 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()
con-structor, 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.27).
Trang 3The 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
erty, which lets you know how many characters there are in a string The prototype
prop-erty allows you to add your own properties and methods to the String object, that is, you
can customize a string
Figure 9.27 Output from Example 9.23.
Table 9.8 String Object Properties
Property What It Does
length Returns the length of the string in characters
constructor Returns the function that created the String object
prototype Extends the definition of the string by adding properties and methods.
E X A M P L E 9 2 4
<html>
<head><title>The String Object</title></head>
<body bgColor="lightblue">
<font face="arial">
<big>
<h3>Length of Strings</h3>
<script type="text/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>
</big>
</font>
</body>
</html>
Trang 4Extending the String Object. Because all objects have the prototype object, it is
possible to extend the properties of a JavaScript built-in String object, just as we did for
a user-defined object (see Chapter 8)
E X P L A N A T I O N
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
opera-tion, 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
co-incidence that both strings are of the same length.) (See Figure 9.28.)
Figure 9.28 Using the String object’s length property.
E X A M P L E 9 2 5
<html>
<head><title>The Prototype Property</title>
<script type = "text/javascript">
// Customize String Functions
var str=this.bold().fontcolor("white").
toUpperCase().fontsize("22");
return(str);
}
</script>
</head>
<body bgcolor="black">
<div align="center">
<script type="text/javascript">
3 var str="Watch Your Step!!";
4 document.write(str.ucLarge()+"<br />");
</script>
<img src="high_voltage.gif">
</div>
</body>
</html>
Trang 5String Methods. There are two types of string methods: the string formatting
meth-ods that mimic the HTML tags they are named for, and the methmeth-ods used to manipulate
a string such as finding a position in a string, replacing a string with another string,
mak-ing a strmak-ing 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
E X P L A N A T I O N
1 The ucLarge() function is defined Its purpose is to generate and return an
upper-case, bold, white font, with a point size of 22
2 The prototype property allows you to customize an object by adding new
proper-ties and methods The name of the customized method is ucLarge, 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(), which performs the
meth-od’s actions and returns a value Using the same name for both the property and
the function reduces the chance of mistakenly calling the method by the wrong
name
3 A new string is created
4 The prototyped method, ucLarge(), is applied to the String object, str It will
mod-ify the string as shown in the output in Figure 9.29
Figure 9.29 Using the String object’s prototype property.
Table 9.9 String Object (HTML) Methods
Method Formats as HTML
String.anchor(Name) <a name="Name">String</a>
String.big() <big>String</big>
String.blink() <blink>String</blink>
Continues
Trang 6String.bold() <b>String</b>
String.fixed() <tt>String</tt>
String.fontcolor(color) <font color="color">String</font>
e.g., <font color="blue">String</font>
String.fontsize(size) <font size="size">String</font>
e.g., <font size="+2">String</font>
String.italics() <i>String</i>
String.link(URL) <a href="URL">String</a>
e.g., <a href="http://www.ellieq.com">String</a>
String.small() <small>String</small>
String.strike() <strike>String</strike> (puts a line through the text)
String.sub() <sub>String</sub> (creates a subscript)
String.sup() <sup>String</sup> (creates a superscript)
E X A M P L E 9 2 6
<html>
<head><title>String object</title></head>
<body bgcolor="yellow">
<big>
<font face="arial">
<h2>Working with String Objects:</h2>
<script type="text/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>
</font>
</big>
</body>
</html>
Table 9.9 String Object (HTML) Methods (continued)
Method Formats as HTML
Trang 7There are a number of methods (see Table 9.10) provided to manipulate a string
E X P L A N A T I O N
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
dis-played in italic, bold, large text (see Figure 9.30)
Figure 9.30 Properties of the String object are used to change its appearance and
determine its size.
Table 9.10 Methods for String Manipulation
charAt(index) Returns the character at a specified index position.
charCodeAt(index) 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.
fromCharCode(codes) Creates a string from a comma-separated sequence of
character codes.
indexOf(substr, startpos) Searches for the first occurrence of substr starting at
startpos and returns the startpos(index value) of substr
lastIndexOf(substr, startpos) Searches for the last occurrence of substr starting at
startpos and returns the startpos (index value) of substr
replace(searchValue, replaceValue) Replaces searchValue with replaceValue.
Continues
Trang 8Methods 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 indexes 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
search(regexp) 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.
toLocaleLowerCase() Returns a copy of the string converted to lowercase.
toLocaleUpperCase() Returns a copy of the string converted to uppercase.
toLowerCase() Converts all characters in a string to lowercase letters.
toString() Returns the same string as the source string.
toUpperCase() Converts all characters in a string to uppercase letters.
valueOf Returns the string value of the object.
E X A M P L E 9 2 7
<html>
<head><title>Substrings</title></head>
<body bgcolor="lightgreen">
<font face="arial"
<big>
Searching for an @ sign
<script type="text/javascript">
1 var email_addr=prompt("What is your email address? ","");
Table 9.10 Methods for String Manipulation (continued)
Trang 92 while(email_addr.indexOf("@") == -1 ){
3 alert( "Invalid email address.");
email_addr=prompt("What is your email address? ","");
} document.write("<br />OK.<br />");
</script>
</big>
</font>
</body>
</html>
E X P L A N A T I O N
1 The user is prompted for his or her 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 @
sym-bol 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.31 and 9.32) 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
dis-cussed in Chapter 17, “Regular Expressions and Pattern Matching.”
Figure 9.31 Using the indexOf() String method.
Figure 9.32 The user entered an e-mail address without the @ symbol.
E X A M P L E
Trang 10E X A M P L E 9 2 8
<html>
<head><title>String Manipulation</title></head>
<body>
<h2>Working with String Manipulation Methods</h2>
<script type="text/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>
E X P L A N A T I O N
1 A new String object is created with the String() constructor.
2 The indexOf() String method returns the index value where “m” is first
encoun-tered in the string starting at the first character, position 0
3 The lastIndexOf() method returns the index position of the last occurrence of “m”
in the string starting from the left from position 0
4 Starting at position 4, the Substr method returns 5 characters
Figure 9.33 Output from Example 9.28.