Question
How to Check if a String Contains a Substring in JavaScript
Question
In JavaScript, how can you check whether one string contains another substring?
A method such as String.contains() might seem like the obvious choice, but that method does not exist in standard JavaScript.
What is the correct and practical way to perform this check?
Example context:
const text = "Hello world";
const search = "world";
How should you test whether text contains search?
Short Answer
By the end of this page, you will understand how to check whether a string contains a substring in JavaScript, when to use includes() versus indexOf(), how case sensitivity works, and what patterns developers commonly use in real code.
Concept
In JavaScript, checking whether a string contains a substring means asking:
- Does this larger string include this smaller piece of text?
- If yes, return
true - If no, return
false
This is a very common operation in programming. You use it when:
- validating user input
- searching text
- filtering data
- checking file paths or URLs
- parsing messages or logs
The modern and most readable way to do this in JavaScript is String.prototype.includes().
const text = "Hello world";
console.log(text.includes("world")); // true
Before includes() became common, developers often used indexOf().
const text = "Hello world";
console.log(text.indexOf("world") !== -1); // true
Both approaches work, but includes() is easier to read because it directly expresses the intent: checking whether the substring exists.
Mental Model
Think of a string like a sentence written on paper.
- The full string is the whole sentence.
- The substring is a word or phrase you are trying to spot.
includes()is like asking: “Can I find this word anywhere in the sentence?”indexOf()is like asking: “At what character position does this word begin?”
If you only care whether it exists, use includes().
If you also care where it appears, use indexOf().
Syntax and Examples
Basic syntax
Using includes()
string.includes(searchString)
string.includes(searchString, startPosition)
searchString: the substring to look forstartPosition: optional index to start searching from- returns
trueorfalse
Example:
const text = "JavaScript is fun";
console.log(text.includes("Script")); // true
console.log(text.includes("Python")); // false
This is the clearest way to test for a substring.
Using indexOf()
string.indexOf(searchString)
string.indexOf(searchString, startPosition)
Step by Step Execution
Consider this example:
const text = "Hello world";
const result = text.includes("world");
console.log(result);
Step by step:
textstores the string"Hello world".- JavaScript evaluates
text.includes("world"). - It scans the string looking for the exact sequence of characters
w,o,r,l,d. - It finds that sequence starting at index
6. - Because the substring exists,
includes()returnstrue. resultnow storestrue.console.log(result)printstrue.
Now compare with :
Real World Use Cases
Checking for substrings appears in many real programs.
Search input filtering
const productName = "Wireless Mouse";
const query = "mouse";
const matches = productName.toLowerCase().includes(query.toLowerCase());
Used in search bars and product filters.
Email validation shortcuts
const email = "user@example.com";
const looksLikeEmail = email.includes("@");
This is not full validation, but it can be part of a quick check.
URL or route checks
const url = "/admin/dashboard";
if (url.includes("/admin")) {
console.log("Admin route");
}
Useful in routing or permission logic.
Log analysis
const logLine = ;
(logLine.()) {
.();
}
Real Codebase Usage
In real codebases, substring checks are often part of larger patterns.
Guard clauses
Developers often exit early when required text is missing.
function processMessage(message) {
if (!message.includes("#")) {
return "Missing tag";
}
return "Valid message";
}
This keeps functions simple and readable.
Input normalization
Case-insensitive matching is very common.
function containsKeyword(text, keyword) {
return text.toLowerCase().includes(keyword.toLowerCase());
}
This prevents failures caused by uppercase/lowercase differences.
Filtering arrays of strings
const users = ["Alice", "Bob", "Charlie"];
const query = "li";
const results = users.filter(
name.().(query.())
);
.(results);
Common Mistakes
1. Trying to use contains()
JavaScript strings do not use contains().
Broken code:
const text = "Hello world";
console.log(text.contains("world"));
Use this instead:
const text = "Hello world";
console.log(text.includes("world"));
2. Forgetting that indexOf() returns 0 for matches at the start
Broken code:
const text = "hello world";
if (text.indexOf("hello")) {
console.log("Found");
}
Why this fails:
indexOf("hello")returns
Comparisons
| Method | Returns | Best use | Example |
|---|---|---|---|
includes() | true or false | Check whether a substring exists | text.includes("cat") |
indexOf() | index or -1 | Find position of first match | text.indexOf("cat") |
startsWith() | true or false | Check whether a string begins with text | text.startsWith("Hello") |
Cheat Sheet
Quick reference
Check if substring exists
str.includes("text")
Check from a starting index
str.includes("text", startIndex)
Older alternative
str.indexOf("text") !== -1
Case-insensitive check
str.toLowerCase().includes(search.toLowerCase())
Useful related methods
str.startsWith("text")
str.endsWith("text")
Rules to remember
includes()returnstrueorfalseindexOf()returns a number or
FAQ
How do I check if a string contains a substring in JavaScript?
Use includes():
"Hello world".includes("world"); // true
Is there a String.contains() method in JavaScript?
No. The standard method is includes().
What is the difference between includes() and indexOf()?
includes()returnstrueorfalseindexOf()returns the starting position or-1
Is includes() case-sensitive?
Yes.
"Hello".includes("hello"); // false
How do I do a case-insensitive contains check?
Mini Project
Description
Build a simple JavaScript text search tool that checks whether a list of messages contains a user-provided keyword. This demonstrates practical substring checking, case-insensitive matching, and filtering results from an array.
Goal
Create a function that returns all messages containing a given search term, regardless of letter case.
Requirements
- Store several text messages in an array.
- Accept a search term as a string.
- Return only the messages that contain the search term.
- Make the search case-insensitive.
- Print the matching results to the console.
Keep learning
Related questions
Deep Cloning Objects in JavaScript: Methods, Trade-offs, and Best Practices
Learn how to deep clone objects in JavaScript, compare structuredClone, JSON methods, and recursive approaches with examples.
Get Screen, Page, and Browser Window Size in JavaScript
Learn how to get screen size, viewport size, page size, and scroll position in JavaScript across major browsers with clear examples.
How JavaScript Closures Work: A Beginner-Friendly Guide
Learn how JavaScript closures work with simple explanations, examples, common mistakes, and practical use cases for real code.