String.prototype.includes()

Summary: in this tutorial, you will learn how to use the JavaScript String includes() method to check if a string contains a substring.

Introduction to JavaScript String includes() method

The includes() method performs a case-sensitive search and determines if a substring is included in a string:

string.includes(searchString [,position])Code language: JavaScript (javascript)

The includes() method returns true if the searchString found in the string or false otherwise:

JavaScript String includes()

The optional position parameter specifies the position within the string at which the method starts searching for the searchString.

The position defaults to 0. This means that if you omit the position, the includes() method will start searching from the beginning of the string.

Note that if you want to know the position of a substring within a string, you can use the indexOf() method.

JavaScript String includes() method examples

Let’s take some examples of using the JavaScript String includes() method.

Basic JavaScript String includes() method example

The following example uses the includes() method to check if the string @ is in the string '[email protected]':

let email = "[email protected]";
const result = email.includes("@");

console.log({ result });Code language: JavaScript (javascript)

Output:

{ result: true }Code language: JavaScript (javascript)

JavaScript includes() method & case sensitivity

The following example uses the includes() method to check if the string 'JavaScript String' includes the substring 'Script':

let str = "JavaScript String";
const result = str.includes("Script");

console.log({ result });Code language: JavaScript (javascript)

Output:

{ result: true }Code language: JavaScript (javascript)

Because the includes() matches the string case-sensitively, the following example returns false:

let str = "JavaScript String";
const result = str.includes("script");

console.log({ result });Code language: JavaScript (javascript)

Output:

falseCode language: JavaScript (javascript)

Using the position parameter

The following example uses the includes() method to search for the string "S" in the string "JavaScript String" starting from index 10:

let str = "JavaScript String";
const result = str.includes("S", 10);

console.log({ result });Code language: JavaScript (javascript)

Output:

{ result: true }Code language: JavaScript (javascript)

Summary

  • Use the JavaScript String includes() method to perform a case-sensitive search and determine if a substring is included in a string.
Was this tutorial helpful ?