Java Reference
In-Depth Information
Chapter 3 talked about the danger of infinite loops, and you can see that there is a danger of one here.
If foundAtPosition++ were removed, you'd keep searching from the same starting point and never
move to find the next occurrence of the word Wrox .
The indexOf() and lastIndexOf() methods are more useful when coupled with the substr() and
substring() methods, which you look at in the next section. Using a combination of these methods
enables you to cut substrings out of a string.
Copying part of a String—the substr() and substring() Methods
If you wanted to cut out part of a string and assign that cut‐out part to another variable or use it
in an expression, you would use the substr() and substring() methods. Both methods provide
the same end result—that is, a part of a string—but they differ in the parameters they require.
The method substring() accepts two parameters: the character start position and the position after
the last character desired in the substring. The second parameter is optional; if you don't include it,
all characters from the start position to the end of the string are included.
For example, if your string is "JavaScript" and you want just the text "Java" , you could call the
method like so:
var myString = "JavaScript";
var mySubString = myString.substring(0,4);
alert(mySubString);
The character positions for the string " JavaScript " are:
CharaCter position
0
1
2
3
4
5
6
7
8
9
Character
J
a
v
a
S
c
r
i
p
t
Like substring() , the method substr() again takes two parameters, the first being the start
position of the first character you want included in your substring. However, this time the second
parameter specifies the length of the string of characters that you want to cut out of the longer
string. For example, you could rewrite the preceding code like this:
var myString = "JavaScript";
var mySubString = myString.substr(0,4);
alert(mySubString);
As with the substring() method, the second parameter is optional. If you don't include it, all the
characters from the start position onward will be included.
Note The substring() method was introduced long before substr() . Most
of the time, you will use the substr() method.
 
Search WWH ::




Custom Search