Find Something Inside a String
JavaScript String Search
Check whether a string contains, starts with, or ends with another string. The methods you'll use to test user input.
What you'll learn
- Use `includes`, `startsWith`, `endsWith` for yes/no checks
- Use `indexOf` to find a position
- Choose between them confidently
When you need to ask “does this string contain X?”, JavaScript has a small kit of search methods that return either a boolean (yes/no) or a position.
includes — yes or no
const sentence = "The quick brown fox jumps over the lazy dog.";
console.log(sentence.includes("fox")); // true
console.log(sentence.includes("cat")); // false
console.log(sentence.includes("Fox")); // false ← case-sensitive includes is the easiest way to ask “does this string contain that
substring?” — use it when you don’t care where, just whether.
startsWith / endsWith
const filename = "report.pdf";
console.log(filename.startsWith("report")); // true
console.log(filename.endsWith(".pdf")); // true
console.log(filename.endsWith(".jpg")); // false
const url = "https://jsschools.com";
console.log(url.startsWith("https://")); // true indexOf — where it is
indexOf(needle) returns the position (0-indexed) of the first
match, or -1 if not found.
const s = "The quick brown fox";
console.log(s.indexOf("brown")); // 10
console.log(s.indexOf("yellow")); // -1
console.log(s.indexOf("o")); // 12 — first o
console.log(s.lastIndexOf("o")); // 17 — last o indexOf is older than includes. If you only need yes/no,
includes reads better:
// Old style:
if (s.indexOf("fox") !== -1) { /* ... */ }
// Modern:
if (s.includes("fox")) { /* ... */ } Case-Insensitive Search
All the search methods are case-sensitive. Lowercase both sides for a case-insensitive check:
const query = "JavaScript";
const text = "I love javascript and TypeScript.";
console.log(text.includes(query)); // false
console.log(text.toLowerCase().includes(query.toLowerCase())); // true Quick Comparison
| Method | Returns | Use when… |
|---|---|---|
includes(needle) | true/false | You just need yes or no |
startsWith(prefix) | true/false | Checking the beginning |
endsWith(suffix) | true/false | Checking the end |
indexOf(needle) | position or -1 | You need the position |
lastIndexOf(needle) | position or -1 | Searching from the right |
Up Next
For inserting variables into strings, JavaScript has a better tool
than +. Template literals.