string.indexOf(character_sequence, start_index)
where string is any literal string value
or an identifier that contains a string;
character_sequence is the string for which
we're searching, which may be a string literal or an identifier
that contains a string; and start_index is
the starting position of the search. If
start_index is omitted, the search starts
at the beginning of string.
Let's use indexOf( ) to check whether a
string contains the character W:
"GWEN!".indexOf("W"); // Returns 1
Yup, W is the second character in
"GWEN!", so we get 1, the index of the
W character. Remember, character indexes start
at 0, so the second character occupies index 1.
What happens if we search for the lowercase character w
? Let's see:
"GWEN!".indexOf("w"); // Returns -1
There is no w in "GWEN!" so
indexOf( ) returns -1. The upper- and lowercase
versions of a letter are different characters and indexOf(
) is case sensitive!
Now let's make sure that there's an @ sign in an email
address:
var email = "daniella2dancethenightaway.ca"; // Oops, someone forgot to
// press Shift!
// If there's no @ sign, warn the user via the formStatus text field
if (email.indexOf("@") == -1) {
formStatus = "The email address is not valid.";
}
We don't always have to search for single characters. We can
search for an entire character sequence in a string too. Let's
look for "Canada" in the address of a company:
var iceAddress = "St. Clair Avenue, Toronto, Ontario, Canada";
iceAddress.indexOf("Canada"); // Returns 36, the index of the letter "C"
Notice that indexOf( ) returns the position of
the first character in "Canada". Now let's compare
the return value of iceAddress.indexOf("Canada")
to -1, and assign the result to a variable that stores the
nationality of the company:
var isCanadian = iceAddress.indexOf("Canada") != -1;
The value of iceAddress.indexOf("Canada") != -1
will be true if
iceAddress.indexOf("Canada") does
not equal -1 ("Canada" is found) and
false if
iceAddress.indexOf("Canada")
does equal -1 ("Canada" is not
found). We then assign that Boolean value to the variable
isCanadian, which we can use to create a
country-specific mailing form for North America:
if (isCanadian) {
mailDesc = "Please enter your postal code.";
} else {
mailDesc = "Please enter your zip code.";
}
The indexOf( ) function can also help us
determine which part of a string we need to extract. We'll see
how that works when we learn about the substring(
) function.