JavaScript String includes() method is used to check if a string contains a substring. If the substring is found, the method returns true. Otherwise, it returns false.
The includes() method is case-sensitive.
Syntax
string.includes(searchString, position)
Parameters
- searchString(required): It is the substring, which we need to search in the String.
- position(optional): The position within the string to begin searching for searchString. (Default 0.).
Return value
It returns true if the string contains the value, otherwise false.
Visual Representation
Example 1: How to Use String includes() Method
text = "Hello Krunal";
result = text.includes("Krunal");
console.log(result);
Output
true
Example 2: Case-sensitive
text = "Hello Krunal";
result = text.includes("Hello");
result1 = text.includes("hello");
console.log(result);
console.log(result1);
Output
true
false
Example 3: Passing two parameters
text = "Hello Krunal";
result = text.includes("r",5);
result1 = text.includes("e",3);
console.log(result);
console.log(result1);
Output
true
false
In this example, the first use case returns true because “r” is found at index 7.
The second use case returns false because the character “e” is at index 1.
Browser compatibility
- Chrome 41 and above
- Edge 12 and above
- Firefox 40 and above
- Opera 28 and above
- Safari 9 and above