What is String.includes() method in JavaScript?

The string.includes() method is used to find out if a string contains a particular substring. It returns true if the substring is found and false otherwise.


Syntax

The first parameter is the case-sensitive substring we are looking for, and the second optional parameter is the index (inclusive) from which we start our search. Indices start from 0 to n-1. We call this method on the string to be searched.

  1. str.includes("hello");
  2. Using optional parameter: str.includes("world", 5);
Using the first syntax
Using the first syntax
Using the optional parameter
Using the optional parameter

Examples

var str = "My name is Arya Stark";
if(str.includes("Arya")){
console.log("word found.");
}
else{
console.log("word NOT found");
}
var str = "I am Lord Varys";
if(str.includes("Lord", 6)){
console.log("word found.");
}
else{
console.log("word NOT found");
}
Copyright ©2024 Educative, Inc. All rights reserved