C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
First: We have a string that contains the final 3 letters of the alphabet. Then we search for 2 of them—and "q" which is not found.
JavaScript program that uses indexOf
var letters = "xyz";
// This is at index 0.
var letterX = letters.indexOf("x");
console.log("RESULT 1: " + letterX);
// This is at index 2.
var letterZ = letters.indexOf("z");
console.log("RESULT 2: " + letterZ);
// Not found, so we get -1 instead of an index.
var letterQ = letters.indexOf("q");
console.log("RESULT 3: " + letterQ);
Output
RESULT 1: 0
RESULT 2: 2
RESULT 3: -1
Here: We pass 0 and the first "cat" string is found. But when we pass 1, we find the second "cat" string as we miss the first.
JavaScript program that uses indexOf, start argument
var words = "cat dog cat";
// Find the word beginning at index 0.
var result1 = words.indexOf("cat", 0);
console.log("RESULT: " + result1);
// Find the word beginning at index 1.
// ... The first instance is not found.
var result2 = words.indexOf("cat", 1);
console.log("RESULT: " + result2);
Output
RESULT: 0
RESULT: 8
JavaScript program that uses lastIndexOf
var words = "cat dog cat";
// Find last occurrence of this substring.
var result = words.lastIndexOf("cat");
console.log("LASTINDEXOF: " + result);
Output
LASTINDEXOF: 8
Tip: This could be implemented with indexOf and a check against -1. But includes is easier to read.
JavaScript program that uses includes
var birds = "parakeet parrot penguin";
// See if the string includes parrot.
if (birds.includes("parrot")) {
console.log("Parrot found");
}
// This word is not found in the string.
if (!birds.includes("zebra")) {
console.log("Zebra not found");
}
Output
Parrot found
Zebra not found