JavaScript String Search, Prefixes and Suffixes
Quick answer
String search methods locate exact, case-sensitive sequences of code units or answer whether a sequence exists.
How it works
indexOf(needle, position) returns the first matching index or -1; lastIndexOf searches from the end toward the beginning with an optional starting position. includes returns a Boolean. startsWith checks at a specified start and endsWith checks before an optional end position. Empty search strings match at valid boundaries. These literal searches do not interpret regex metacharacters.
const name = "report.txt";console.log(name.startsWith("rep"), name.endsWith(".txt"));Expected output in Node.js:
true trueBoth exact boundaries match.
const text = "bananas";console.log(text.indexOf("ana"), text.lastIndexOf("ana"), text.includes("ANA"));Expected output in Node.js:
1 3 falseOverlapping occurrences start at 1 and 3; the uppercase query differs.
Common mistakes
Never use if (text.indexOf(needle)): a match at zero is falsy and -1 is truthy. Compare against -1 or use includes.
Practice
Check whether filenames end in a literal suffix, including uppercase and missing extensions.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript String Search, Prefixes and Suffixes — Knowledge Check
Apply the taught concept and predict the output.
Which result indicates an unsuccessful indexOf search?
Which method is appropriate for a simple Boolean containment test?
What does an optional endPosition in endsWith specify?
What is the exact console output in JavaScript String Search, Prefixes and Suffixes example 1?
const name = "report.txt";console.log(name.startsWith("rep"), name.endsWith(".txt"));What is the exact console output in JavaScript String Search, Prefixes and Suffixes example 2?
const text = "bananas";console.log(text.indexOf("ana"), text.lastIndexOf("ana"), text.includes("ANA"));