JavaScript String includes() Method

Created with Sketch.

JavaScript String includes() Method

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

Introduction to JavaScript String includes() method

The includes() method determines whether a string contains another string:

string.includes(searchString [,position])

Code language: CSS (css)

The includes() method returns true if the searchString found in the string; otherwise false.

The optional position parameter specifies the position within the string at which to begin searching for the searchString. The position defaults to 0.

The includes() matches string case-sensitively.

JavaScript String includes() examples

This example uses the includes() method to check if the string @ is in the string 'admin@example.com':

let email = 'admin@example.com';
console.log(email.includes('@'));

Code language: JavaScript (javascript)

Output:

true

Code language: JavaScript (javascript)

The following example checks if the str contains the Script:

let str = 'JavaScript String';
console.log(str.includes('Script'));

Code language: JavaScript (javascript)

Output:

true

Code language: JavaScript (javascript)

As mentioned earlier, the includes() matches the string case-sensitively, therefore, the following example returns false:

let str = 'JavaScript String';
console.log(str.includes('script'));

Code language: JavaScript (javascript)

Output:

false

Code language: JavaScript (javascript)

The following example uses the includes() method with the second parameter:

let str = 'JavaScript String';
console.log(str.includes('Script', 5));

Code language: JavaScript (javascript)

Output:

false

Code language: JavaScript (javascript)

In this tutorial, you have learned how to use the JavaScript String includes() method to determine whether a string contains another string.

Leave a Reply

Your email address will not be published. Required fields are marked *