Java Reference
In-Depth Information
However, as you have seen, you can also declare a string primitive and use it as if it were a String
object, letting JavaScript do the conversion to an object for you behind the scenes. For example:
var string1 = “Hello”;
Using this technique is preferable so long as it's clear to JavaScript what object you expect to have cre-
ated in the background. If the primitive data type is a string, this won't be a problem and JavaScript
will work it out. The advantages to doing it this way are that there is no need to create a String object
itself and you avoid the troubles with comparing string objects. When you try to compare string objects
with primitive string values, the actual values are compared, but with String objects, the object refer-
ences are compared.
The String object has a vast number of methods and properties. In this section, you'll be looking only
at some of the less complex and more commonly used methods. However, in Chapter 9 you'll look at
some of the trickier but very powerful methods associated with strings and the regular expression
object (RegExp). Regular expressions provide a very powerful means of searching strings for patterns
of characters. For example, if you want to fi nd “Paul” where it exists as a whole word in the string
“Pauline, Paul, Paula”, you need to use regular expressions. However, they can be a little tricky to
use, so we won't discuss them further in this chapter — we want to save some fun for later!
With most of the String object's methods, it helps to remember that a string is just a series of individual
characters and that, as with arrays, each character has a position, or index. Also as with arrays, the fi rst
position, or index, is labeled 0 and not 1. So, for example, the string “Hello World” has the character
positions shown in the following table:
Character Index
0
1
2
3
4
5
6
7
8
9
10
Character
H
e
l
l
o
W
o
r
l
d
The length Property
The length property simply returns the number of characters in the string. For example,
var myName = new String(“Jeremy”);
document.write(myName.length);
will write the length of the string “Jeremy” (that is, 6 ) to the page.
Finding a String Inside Another String — The indexOf() and
lastIndexOf() Methods
The methods indexOf() and lastIndexOf() are used for searching for the occurrence of one string
inside another. A string contained inside another is usually termed a substring . They are useful when
you have a string of information but only want a small part of it. For example, in the trivia quiz, when
someone enters a text answer, you want to check if certain keywords are present within the string.
Both indexOf() and lastIndexOf() take two parameters:
The string you want to fi nd
The character position you want to start searching from (optional)
Search WWH ::




Custom Search