includes(): Checking for Substrings
What you'll learn: How to quickly check if a string contains a specific substring anywhere inside it.
What is includes()?
The includes() method is your go-to tool when you need to answer a simple yes-or-no question: "Does this string contain this piece of text?" It returns true if the substring is found anywhere in the string, and false if it's not.
Think of it like using Ctrl+F (Find) in a document. You're not trying to extract or replace the text—you just want to know: Is it in here?
Basic Syntax
string.includes(searchString)
Examples
const greeting = "Hello, world!";
greeting.includes("world"); // true
greeting.includes("World"); // false (case-sensitive!)
greeting.includes("o"); // true
greeting.includes("xyz"); // false
Notice that includes() is case-sensitive—it treats "world" and "World" as completely different strings.
Checking from a Starting Position
You can provide an optional second argument to tell includes() where to start searching:
const message = "JavaScript is awesome";
message.includes("is"); // true
message.includes("is", 10); // false (starts searching from index 10)
message.includes("awesome", 15); // true (found at index 15)
Practical Use
const email = "user@example.com";
if (email.includes("@")) {
// Basic validation: email contains @ symbol
}
Key Takeaway: Use includes() when you need a simple true/false answer about whether a substring exists anywhere in your string—it's straightforward, readable, and case-sensitive.