Java Reference
In-Depth Information
The String object has a vast number of methods and properties. In this section, you look only at
some of the less complex and more commonly used methods. However, in Chapter 6 you 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 find "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 first 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 = "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 find
The character position you want to start searching from (optional)
Character positions start at 0 . If you don't include the second parameter, searching starts from the
beginning of the string.
The return value of indexOf() and lastIndexOf() is the character position in the string at which
the substring was found. Again, it's zero‐based, so if the substring is found at the start of the string,
then 0 is returned. If there is no match, the value ‐1 is returned.
 
Search WWH ::




Custom Search