Java Reference
In-Depth Information
For example, to search for the substring
"Jeremy"
in the string
"Hello jeremy.
How are you Jeremy"
, you can use the following code:
var myString = "Hello jeremy. How are you Jeremy";
var foundAtPosition = myString.indexOf("Jeremy");
alert(foundAtPosition);
This code should result in a message box containing the number
26
, which is the character position
of
"Jeremy"
. You might be wondering why it's
26
, which clearly refers to the second
"Jeremy"
in the
string, rather than
6
for the first
"jeremy"
.
This is due to case sensitivity. JavaScript takes case sensitivity very seriously, both in its syntax and
when making comparisons. If you type
IndexOf()
instead of
indexOf()
, JavaScript will complain.
Similarly,
"jeremy"
is not the same as
"Jeremy"
. Remember that mistakes with case are very common
and so easy to make, even for experts, and it's best to be very aware of case when programming.
You've seen
indexOf()
in action, but how does
lastIndexOf()
differ? Well, whereas
indexOf()
starts
searching from the beginning of the string, or the position you specified in the second parameter, and
works toward the end,
lastIndexOf()
starts at the end of the string, or the position you specified, and
works toward the beginning of the string. Let's modify the previous example to the following code:
var myString = "Hello Jeremy. How are you Jeremy";
var foundAtPosition = myString.indexOf("Jeremy");
alert(foundAtPosition);
foundAtPosition = myString.lastIndexOf("Jeremy");
alert(foundAtPosition);
First, notice the string value assigned to
myString
; both instances of
"Jeremy"
now begin with a
capital letter. The first
alert
box displays the result of
6
because that is the position of the first
occurrence of
"Jeremy"
. The second
alert
box displays
26
because
lastIndexOf()
starts searching
at the end of the string, and the position of the first occurrence of
"Jeremy"
from the end of the
string is
26
.
trY it out
Counting Occurrences of Substrings
In this example, you look at how to use the “start character position” parameter of
indexOf()
. Here
you will count how many times the word Wrox appears in the string:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 5, Example 1</title>
</head>
<body>
<script>