JavaScript Reference ยท String
String.prototype.includes()
Reference for JavaScript String.prototype.includes(): test whether a string contains some text, use the start position, and handle case and regex pitfalls.
The includes() method reports whether one string appears anywhere inside another. It returns true or false, which makes it the natural choice when you only need a yes-or-no answer.
Before it existed, people wrote text.indexOf("word") !== -1. includes() says the same thing in plain words.
"JavaScript".includes("Script"); // true
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
string.includes(searchString) string.includes(searchString, position)
| Name | Description |
|---|---|
searchString |
The text to look for. It is converted to a string. A regular expression is rejected. |
position |
Optional. The index where the search starts. Defaults to 0. Negative values count as 0, and values past the end are clamped to the length. |
Return value: true if searchString occurs at or after position, otherwise false.
Exceptions: a TypeError if searchString is a regular expression.
Usage notes
- Case-sensitive. Normalize both sides with
toLowerCase()for a case-insensitive check. For text in many languages,localeCompare()orIntl.Collatorhandle accents and case rules better. positionis where the search starts, not where a match must start."The quick brown fox".includes("quick", 5)isfalsebecause the word begins at index4.- An empty string is always found, so
text.includes("")istrueeven for an emptytext. Guard user input before calling it. - No regular expressions. Passing one throws, to avoid surprising literal matching. Use
RegExp.prototype.test()for patterns. - You do not get the position. If you need it, use
indexOf(). - Not the array method.
Array.prototype.includes()compares whole elements, while the string version looks for a substring."abc".includes("bc")istrue, but["abc"].includes("bc")isfalse. SeeArray.prototype.includes(). - Performance: a simple scan, fast for ordinary text. For searching large documents repeatedly, build an index instead of calling it in a tight loop.
Browser support
includes() is part of ES2015 and works in all current browsers.