Sub topic 5
Finding Text Inside a String
This chapter assumes you can write functions and loops, know that string indexes start at 0, and can run code in Node.js or a browser console. Regular expression searching comes in a later chapter. Here the focus is on the five methods that search for plain text: indexOf, lastIndexOf, includes, startsWith, and endsWith.
The methods split into two groups. indexOf and lastIndexOf tell you where a match is. includes, startsWith, and endsWith tell you whether there is a match. Choosing the wrong group is the most common source of bugs here.
The Methods at a Glance
| Method | Returns | Second argument | Accepts a RegExp? |
|---|---|---|---|
| `indexOf(search, from)` | First index, or `-1` | Index where the forward search starts | No (converts it to a string) |
| `lastIndexOf(search, from)` | Last index, or `-1` | Latest index a match may start at | No (converts it to a string) |
| `includes(search, from)` | `true` or `false` | Index where the search starts | No (throws `TypeError`) |
| `startsWith(search, pos)` | `true` or `false` | Index treated as the start | No (throws `TypeError`) |
| `endsWith(search, end)` | `true` or `false` | Length treated as the end | No (throws `TypeError`) |
All five are case-sensitive. They compare UTF-16 code units exactly, so "A" never matches "a".
Finding Positions with indexOf and lastIndexOf
indexOf scans forward and returns the index of the first character of the first match. lastIndexOf scans backward and returns the start index of the last match. Both return -1 when nothing matches.
const s = "the cat sat on the mat";
console.log(s.indexOf("the")); // 0
console.log(s.indexOf("the", 1)); // 15 (search starts at index 1)
console.log(s.lastIndexOf("the")); // 15
console.log(s.lastIndexOf("the", 14)); // 0
console.log(s.indexOf("dog")); // -1
console.log(s.indexOf("at")); // 5
console.log(s.lastIndexOf("at")); // 20
console.log(s.lastIndexOf("at", 19)); // 9
console.log(s.lastIndexOf("at", 20)); // 20 (match runs past index 20, still allowed)How the Second Argument Works
For indexOf, the second argument is where the forward scan begins. A match at or after that index counts. Negative values are clamped to 0, and values past the end are clamped to the string's length.
For lastIndexOf, the second argument is the latest index at which a match may start. The match itself may extend past that index. The last line above shows this: "at" starting at 20 occupies indexes 20 and 21, and lastIndexOf("at", 20) still finds it. If you expected the argument to be an end boundary, as with endsWith, you will get results that look off by a few characters.
Yes-or-No Checks with includes, startsWith, and endsWith
When you only need a boolean, use the methods that return one. They make your intent clear and avoid the -1 comparison entirely.
const file = "report-2026.PDF";
console.log(file.startsWith("report")); // true
console.log(file.includes("2026")); // true
console.log(file.endsWith(".pdf")); // false (case differs)
console.log(file.toLowerCase().endsWith(".pdf")); // true
console.log(file.startsWith("2026", 7)); // true (pretend the string starts at 7)
console.log(file.endsWith("report", 6)); // true (pretend the length is 6)
console.log(file.includes("report", 1)); // false (search starts at index 1)startsWith(search, pos) checks whether the text beginning at pos matches. This works well when parsing, because you can check for a token at the current cursor position without cutting the string first.
endsWith(search, end) treats the string as if it were only end characters long. file.endsWith("report", 6) looks only at "report", the first six characters.
Case-Insensitive Checks
None of these methods has a case-insensitive option. The usual workaround converts both sides to the same case:
function includesIgnoreCase(haystack, needle) {
return haystack.toLowerCase().includes(needle.toLowerCase());
}
console.log(includesIgnoreCase("Hello World", "WORLD")); // trueThis is fine for English text. Case mapping in some languages, Turkish dotted and dotless i for example, needs locale-aware handling, which the chapter on locale comparison covers.
The -1 Trap
indexOf returns 0 for a match at the very start and -1 for no match. In a boolean context, 0 is falsy and -1 is truthy. Treating the result as a boolean therefore gets both cases backwards:
const greeting = "hello world";
// Wrong: a match at index 0 is falsy, and "no match" (-1) is truthy
if (greeting.indexOf("hello")) {
console.log("found hello"); // never runs
}
if (greeting.indexOf("xyz")) {
console.log("found xyz"); // runs, incorrectly
}
// Right
if (greeting.indexOf("hello") !== -1) {
console.log("found hello"); // runs
}
// Clearer, when you do not need the position
if (greeting.includes("hello")) {
console.log("found hello"); // runs
}Older code sometimes writes ~s.indexOf(x), which turns -1 into 0 and every other value into something nonzero. It works, but includes says the same thing more readably.
Finding Every Occurrence
None of these methods returns all matches. To find every match, call indexOf in a loop and pass the next start position each time. You have to decide whether matches may overlap. To allow overlaps, advance by 1. To skip past each match, advance by the length of the search string.
function findAll(haystack, needle, { overlap = false } = {}) {
if (needle === "") {
throw new RangeError("needle must not be empty");
}
const positions = [];
const step = overlap ? 1 : needle.length;
let i = haystack.indexOf(needle);
while (i !== -1) {
positions.push(i);
i = haystack.indexOf(needle, i + step);
}
return positions;
}
console.log(findAll("banana", "ana")); // [1]
console.log(findAll("banana", "ana", { overlap: true })); // [1, 3]
console.log(findAll("aaaa", "aa")); // [0, 2]
console.log(findAll("aaaa", "aa", { overlap: true })); // [0, 1, 2]
console.log(findAll("hello", "z")); // []The guard against an empty needle matters. indexOf("") matches at every position. With a step of needle.length, which is 0, the loop would never advance and would run forever.
Edge Cases and Argument Coercion
These methods convert their search argument to a string before searching. That rule causes several surprising results:
// Empty search strings match everywhere
console.log("abc".indexOf("")); // 0
console.log("abc".indexOf("", 10)); // 3 (position clamped to length)
console.log("abc".lastIndexOf("")); // 3
console.log("abc".includes("")); // true
console.log("abc".startsWith("")); // true
console.log("abc".endsWith("")); // true
// Negative start positions are clamped to 0
console.log("abc".indexOf("c", -5)); // 2
// Non-string arguments are converted to strings
console.log("null or undefined".includes(null)); // true (searches "null")
console.log("undefined".includes()); // true (searches "undefined")
console.log("a1".includes(1)); // true (searches "1")
// A RegExp is converted to its source text by indexOf...
console.log("abc".indexOf(/b/)); // -1 (searches for the text "/b/")
// ...but rejected by the boolean methods
try {
"abc".includes(/b/);
} catch (e) {
console.log(e.name); // TypeError
}In practice, two rules follow from this. First, check for an empty or missing search value before searching, especially when the value comes from user input. An empty search box makes every item "match". A missing argument searches for the literal text "undefined". Second, never pass a regular expression to indexOf. It will not throw. It will search for the regex's text and quietly return -1. Use search instead, which a later chapter covers.
Combining Search with Extraction
Search methods usually feed an index into slice. A common pattern is "everything after the last separator":
const path = "/docs/guide/strings.md";
console.log(path.includes("guide")); // true
console.log(path.startsWith("/docs")); // true
console.log(path.endsWith(".md")); // true
console.log(path.indexOf("/", 1)); // 5
const lastSlash = path.lastIndexOf("/");
console.log(path.slice(lastSlash + 1)); // strings.mdThis works even when there is no slash at all. lastIndexOf returns -1, -1 + 1 is 0, and slice(0) returns the whole string. When the code depends on that kind of fallback, add a comment saying so, because readers will otherwise suspect a bug.
Exercise
What does each line print, and why? (1) "Mississippi".lastIndexOf("ss", 4) (2) "Mississippi".indexOf("ss", 3) (3) "Mississippi".endsWith("ss", 4)
Show answer
(1) 2. "ss" starts at indexes 2 and 5. lastIndexOf only accepts matches that start at or before 4, so the answer is 2. (2) 5. The forward search begins at index 3, skipping the match at 2. (3) true. endsWith treats the string as its first 4 characters, "Miss", which ends with "ss".
Exercise
A filter function is written as items.filter((item) => item.indexOf(query)). Describe two separate bugs in it and give a corrected version.
Show answer
First, indexOf returns 0 for a match at the start, which is falsy, so those items are dropped. It returns -1 for no match, which is truthy, so non-matching items are kept. Second, if query is an empty string every item matches, and if query is undefined the code searches for the text "undefined". A corrected version: const q = (query ?? "").trim(); const result = q === "" ? items : items.filter((item) => item.includes(q));
Exercise
Write a function countOccurrences(text, word) that returns how many non-overlapping times word appears in text using only indexOf, and returns 0 for an empty word. What does it return for ("aaaaa", "aa")?
Show answer
function countOccurrences(text, word) { if (word === "") return 0; let count = 0; let i = text.indexOf(word); while (i !== -1) { count++; i = text.indexOf(word, i + word.length); } return count; } For ("aaaaa", "aa") it returns 2: matches at indexes 0 and 2. The next search starts at 4, and only one "a" is left there.