Choosing the Right Search Method
You'll learn how to pick the most efficient and readable string search method for any task.
JavaScript offers several ways to search strings — includes(), indexOf(), search(), and match() — and choosing the right one makes your code clearer and faster.
Decision Guide
Use includes() when you only need a yes/no answer: "Does this string contain 'error'?" It returns true or false and is the most readable for simple checks.
if (message.includes('error')) {
console.log('Something went wrong!');
}
Use indexOf() when you need the position of a substring, or when checking existence in older code. It returns the index (or -1 if not found). Bonus: you can search starting from a specific position.
const pos = url.indexOf('://');
const protocol = url.substring(0, pos); // extract "https"
Use search() when you need a regex pattern and only care about the first match position. It's like indexOf() but with pattern power.
const firstDigit = text.search(/\d/); // find first number
Use match() when you need to extract matched content, not just find it. With global regex, you get all matches as an array.
const numbers = text.match(/\d+/g); // ["42", "100", "7"]
The Mental Model
Think of it like tools in a toolbox: includes() is a magnet (does it stick?), indexOf() is a ruler (where is it?), search() is a pattern stencil, and match() is scissors (cut out what fits).
Key Takeaway: Use includes() for existence checks, indexOf() for position with plain strings, search() for regex position-finding, and match() for extracting matched content.