Sub topic 5
Finding Text Inside a String
This chapter assumes you know basic JavaScript syntax, can run code in Node.js or a browser console, and know from earlier chapters that string indexes start at 0.
JavaScript has five built-in methods for finding text inside a string. Two of them return a position, and three return true or false. Choosing the right one makes your code shorter and helps you avoid one very common bug.
Position Methods: indexOf and lastIndexOf
indexOf(search, fromIndex) returns the index of the first match, or -1 if there is no match. lastIndexOf(search, fromIndex) searches backward and returns the index of the last match. In both methods, the optional second argument sets where the search starts.
const path = "/docs/guide/strings.md";
console.log(path.indexOf("/")); // 0
console.log(path.indexOf("/", 1)); // 5 (search starts at index 1)
console.log(path.lastIndexOf("/")); // 11
console.log(path.lastIndexOf("/", 10)); // 5 (search backward from index 10)
console.log(path.indexOf("x")); // -1 (not found)Use these methods when you need the location itself, for example to cut a string at that point or to step through every occurrence:
function countOccurrences(text, word) {
if (word === "") return 0; // an empty string matches everywhere
let count = 0;
let pos = text.indexOf(word);
while (pos !== -1) {
count++;
pos = text.indexOf(word, pos + word.length);
}
return count;
}
console.log(countOccurrences("banana", "an")); // 2
console.log(countOccurrences("banana", "x")); // 0Boolean Methods: includes, startsWith, endsWith
When you only need a yes or no answer, these three methods say what you mean directly:
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.startsWith("guide", 6)); // true (check from index 6)
console.log(path.endsWith("guide", 11)); // true (treat the string as 11 characters long)
console.log(path.includes("Guide")); // false (searches are case-sensitive)The second argument of endsWith works differently from the others. It gives the end position: the string is treated as if it were only that many characters long.
| Method | Returns | Optional second argument |
|---|---|---|
| `indexOf` | first index or `-1` | start position |
| `lastIndexOf` | last index or `-1` | position to search backward from |
| `includes` | boolean | start position |
| `startsWith` | boolean | start position |
| `endsWith` | boolean | end position |
Common Errors
Treating indexOf as a boolean
A match at index 0 returns 0, and 0 is falsy. The check below fails even though the text is present:
const s = "hello";
if (s.indexOf("h")) {
console.log("found"); // never runs: indexOf returned 0
}
if (s.indexOf("h") !== -1) {
console.log("found"); // runs
}
if (s.includes("h")) {
console.log("found"); // runs, and reads more clearly
}Forgetting case sensitivity
All five methods compare characters exactly. To search without regard to case, convert both strings to the same case first: text.toLowerCase().includes(query.toLowerCase()).
Passing a regular expression
indexOf converts a regex to a string and searches for that literal text. includes, startsWith, and endsWith throw an error instead:
try {
"abc".includes(/a/);
} catch (e) {
console.log(e instanceof TypeError); // true
}Exercise
Given const file = "report.final.pdf", write one expression that returns the index of the dot before the extension, and explain why if (file.indexOf("r")) does not detect the "r" at the start.
Show answer
file.lastIndexOf(".") returns 12, the index of the last dot. file.indexOf("r") returns 0 because "r" is the first character, and 0 is falsy, so the if block is skipped. Use file.indexOf("r") !== -1 or file.includes("r") instead.
Exercise
What do "filename.txt".endsWith("name", 8) and "filename.txt".startsWith("name", 4) return?
Show answer
Both return true. endsWith treats the string as its first 8 characters, "filename", which ends with "name". startsWith begins checking at index 4, where "name" starts.