JavaScript String Search

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.

4 min read Level 1/5 #strings#search#includes
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

includes script.js
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
▶ Preview: console

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

startsWith and endsWith script.js
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
▶ Preview: console

indexOf — where it is

indexOf(needle) returns the position (0-indexed) of the first match, or -1 if not found.

indexOf script.js
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
▶ Preview: console

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")) { /* ... */ }

All the search methods are case-sensitive. Lowercase both sides for a case-insensitive check:

Case-insensitive includes script.js
const query = "JavaScript";
const text = "I love javascript and TypeScript.";

console.log(text.includes(query));                    // false
console.log(text.toLowerCase().includes(query.toLowerCase())); // true
▶ Preview: console

Quick Comparison

MethodReturnsUse when…
includes(needle)true/falseYou just need yes or no
startsWith(prefix)true/falseChecking the beginning
endsWith(suffix)true/falseChecking the end
indexOf(needle)position or -1You need the position
lastIndexOf(needle)position or -1Searching from the right

Up Next

For inserting variables into strings, JavaScript has a better tool than +. Template literals.

JavaScript Template Literals →