Java Reference
In-Depth Information
var myString = "Welcome to Wrox topics. " +
"The Wrox website is
www.wrox.com.
" +
"Visit the Wrox website today. Thanks for buying Wrox";
var foundAtPosition = 0;
var wroxCount = 0;
while (foundAtPosition != -1) {
foundAtPosition = myString.indexOf("Wrox", foundAtPosition);
if (foundAtPosition != -1) {
wroxCount++;
foundAtPosition++;
}
}
document.write("There are " + wroxCount + " occurrences of the word Wrox");
</script>
</body>
</html>
Save this example as
ch5 _ example1.html
. When you load the page into your browser, you should see
the following sentence:
There are 4 occurrences of the word Wrox.
At the top of the script block, you built up a string inside the variable
myString
, which you then want
to search for the occurrence of the word
Wrox
. You also define two variables:
wroxCount
will contain
the number of times
Wrox
is found in the string, and
foundAtPosition
will contain the position in the
string of the current occurrence of the substring
Wrox
.
You then used a
while
loop, which continues looping all the while you are finding the word
Wrox
in the
string—that is, while the variable
foundAtPosition
is not equal to
‐1
. Inside the
while
loop, you have
this line:
foundAtPosition = myString.indexOf("Wrox", foundAtPosition);
Here you search for the next occurrence of the substring
Wrox
in the string
myString
. How do you
make sure that you get the next occurrence? You use the variable
foundAtPosition
to give you the
starting position of your search, because this contains the index after the index position of the last
occurrence of the substring
Wrox
. You assign the variable
foundAtPosition
to the result of your
search, the index position of the next occurrence of the substring
Wrox
.
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.