String. prototype. includes()
Checks whether a string contains the given piece of text. Returns true or false, and is case-sensitive.
- Returns
trueif the piece of text appears in the string,falseotherwise.- Changes the original
- No
Example
#const description = 'JavaScript course for beginners'
console.log(description.includes('JavaScript'))
console.log(description.includes('javascript'))
console.log(description.includes('Python'))Definition and usage
#The includes() method answers a simple question: does this piece of text appear in the string? It returns true or false, so it works great in if conditions and for filtering lists.
The comparison is case-sensitive, so "JavaScript".includes("script") returns false. To search regardless of letter case, lowercase both sides first. The second, optional argument marks the index where the search starts.
The method only accepts text. Passing a regular expression throws a TypeError, since match() and RegExp.prototype.test() exist for patterns. An empty string "" is contained in every piece of text.
Syntax
#string.includes(searchString)
string.includes(searchString, position)Parameters
#searchString
string
The piece of text to search for. A regular expression throws aTypeError.position
number, optional
The index where the search starts. Defaults to0.
More examples
#const lessons = ['Variables and types', 'For loops', 'Arrow functions']
const query = 'LOOPS'
const found = lessons.filter((lesson) => lesson.toLowerCase().includes(query.toLowerCase()))
console.log(found)const code = 'let a = 1; let b = 2'
console.log(code.includes('let', 1))
console.log(code.includes('let', 12))const comment = 'Great lesson, but too few examples'
const keywords = ['bug', 'example', 'unclear']
console.log(keywords.some((word) => comment.includes(word)))Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#startsWith()andendsWith()are more readable when checking the start or end of text.- If you need the position of the match, not just a yes-or-no answer, use
indexOf().
Related entries
#- String.prototype.indexOf()Returns the index of the first occurrence of the given text in a string, or -1 when it is not there.
- String.prototype.startsWith()Checks whether a string starts with the given text. Returns true or false.
- String.prototype.endsWith()Checks whether a string ends with the given text. Returns true or false.
- String.prototype.match()Matches a string against a regular expression. Returns an array with the match or all matches, or null.
- Array.prototype.includes()Checks whether an array contains the given value.
Spotted a mistake or missing an example? Write to us.