indexOf ExamplesΒΆ

The general syntax for this method is:

stringName.indexOf(substr);

Given a candidate substring, this method returns the integer index of the first occurrence of the substring in the string. If the substring does not occur in the string, -1 is returned.

Example

1console.log("LaunchCode".indexOf("C"));
2
3console.log("LaunchCode".indexOf("A"));
4
5console.log("dogs and dogs and dogs!".indexOf("dog"));

Output

6
-1
0

Example

An email address must contain an @ symbol. Checking for the presence of this symbol is a part of email address verification in most programs.

1let input = "[email protected]";
2let atIndex = input.indexOf("@");
3
4if (atIndex > -1) {
5   console.log("Email contains @");
6} else {
7   console.log("Invalid email");
8}

Output

Email contains @