String search
- Node.js course
- Beginner
- Lesson 31/116
- 4 min
Learn to search with .indexOf, .includes and .startsWith.
Searching with indexOf
To find a substring's position you use the .indexOf() method. "hello world".indexOf("world") returns 6 because "world" starts at index 6. Indexing is zero-based.
If the substring is not found .indexOf() returns -1. This value is often used to check whether a substring exists: if (text.indexOf("@") !== -1) roughly tests whether a text might be an email.
includes and startsWith
.includes() returns true/false for whether a substring exists in a string: "welcome".includes("come") evaluates to true. It is a more readable form of .indexOf() !== -1.
.startsWith() tests whether a string begins with the given substring: "Mr. Smith".startsWith("Mr.") is true. Its counterpart .endsWith() checks the end. All three methods are case-sensitive.
Practice Find and print the index
The sentence variable holds "Node.js rocks". Declare a variable pos and assign the result of sentence.indexOf("rocks") to it. Then print pos with console.log. The output on a single line must be 8.
Starter code
const sentence = "Node.js rocks";
// Declare pos with indexOf and print itSample solution
const sentence = "Node.js rocks";
const pos = sentence.indexOf("rocks");
console.log(pos);Expected output
8
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each method to its job
| Term | Meaning |
|---|---|
.indexOf(x) |
Returns first index |
.includes(x) |
Asks whether it exists |
.startsWith(x) |
Checks the start |
.length |
Character count |
2 What is the result of "notebook".includes("book")?
"notebook".includes("book")- false
- -1
- 4
- true Correct answer
Explanation: "book" is in "notebook"; includes returns true.
3 Write the startsWith call
const code = "US-CA";
const ok = code____("US-");
const code = "US-CA";
const ok = code.startsWith("US-");
Explanation: .startsWith checks the start of the string.