JavaScriptStrings

String.prototype.includes()

Checks whether a string contains the given piece of text. Returns true or false, and is case-sensitive.

Returns
true if the piece of text appears in the string, false otherwise.
Changes the original
No
On this page

Example

#
JavaScript
const description = 'JavaScript course for beginners'

console.log(description.includes('JavaScript'))
console.log(description.includes('javascript'))
console.log(description.includes('Python'))
Console
true
false
false

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

#
Syntax
string.includes(searchString)
string.includes(searchString, position)

Parameters

#
  • searchString

    string

    The piece of text to search for. A regular expression throws a TypeError.
  • position

    number, optional

    The index where the search starts. Defaults to 0.

More examples

#
A case-insensitive search
JavaScript
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)
Console
['For loops']
Searching from a chosen index
JavaScript
const code = 'let a = 1; let b = 2'

console.log(code.includes('let', 1))
console.log(code.includes('let', 12))
Console
true
false
A few keywords
JavaScript
const comment = 'Great lesson, but too few examples'
const keywords = ['bug', 'example', 'unclear']

console.log(keywords.some((word) => comment.includes(word)))
Console
true

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • startsWith() and endsWith() 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

#

Spotted a mistake or missing an example? Write to us.