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
1 2 3 4 5 | console.log("LaunchCode".indexOf("C"));
console.log("LaunchCode".indexOf("A"));
console.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.
1 2 3 4 5 6 7 8 | let input = "[email protected]";
let atIndex = input.indexOf("@");
if (atIndex > -1) {
console.log("Email contains @");
} else {
console.log("Invalid email");
}
|
Output
Email contains @