The JavaScript string.includes() method
The includes() method checks whether a string contains another string and returns true or false. "Hello world".includes("world") is true. It's the clear, modern replacement for indexOf(x) !== -1, and it's case-sensitive.
Overview
includes() answers a simple question: does this string contain that text? It returns a boolean, which reads much better than the old str.indexOf("x") !== -1 idiom. Use it for searching — does the input contain an "@", does the URL include "https", is a keyword present in the title.
It's case-sensitive, so "Hello".includes("hello") is false. When case shouldn't matter, lowercase both sides first: str.toLowerCase().includes(term.toLowerCase()). You can also pass a second argument, a position, to start the search from a given index.
If you specifically need the position of the match, use indexOf() instead. And to check only the start or end of a string, the dedicated startsWith() and endsWith() methods are clearer than a general includes(). There's also an array version of includes() for checking membership in a list.
Syntax
const has = str.includes(searchString)
const has = str.includes(searchString, position)
Parameters
The string.includes() method accepts the following parameters.
| Parameter | Description |
|---|---|
searchString |
The text to look for. The match is case-sensitive. |
position |
Optional. The index to start searching from. Defaults to 0. |
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const title = 'Learn JavaScript Fast';
document.getElementById('out').textContent =
'has JavaScript? ' + title.includes('JavaScript') + '\n' +
'has python? ' + title.toLowerCase().includes('python');
// has JavaScript? true / has python? false
</script>
Best practices
- Prefer
includes()overindexOf(x) !== -1for a readable presence check. - Lowercase both strings first for a case-insensitive search.
- Use
startsWith()/endsWith()when you only care about the beginning or end. - Need the position, not just yes/no? Use indexOf().
Frequently asked questions
How do I check if a string contains a substring?
str.includes("text"), which returns true or false.Is string includes() case-sensitive?
"Hello".includes("hello") is false. Lowercase both sides for a case-insensitive check.What is the difference between includes() and indexOf()?
includes() returns a boolean; indexOf() returns the position (or -1). Use includes() when you only need yes/no.How do I check the start of a string?
str.startsWith("text") — clearer than includes() when position matters.