Java Reference
In-Depth Information
Each time Wrox is found (that is, each time foundAtPosition is not -1) you increase the variable
wroxCount, which counts how many times you have found the substring, and you increase
foundAtPosition so that you continue the search at the next position in the string.
if (foundAtPosition != -1)
{
wroxCount++;
foundAtPosition++;
}
Finally, you document.write() the value of the variable wroxCount to the page.
Chapter 3 talked about the danger of infi nite 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 fi nd 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'll be looking 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 character 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);
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 fi rst being the start position
of the fi rst character you want included in your substring. However, this time the second parameter
specifi es 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);
Search WWH ::




Custom Search