Description
The JavaScript method includes() checks if a string contains a specific string.
- The method is case-sensitive.
Syntax
The method checks if str contains searchString from index defined by position to end of the str.
str.includes(searchString, position)
Parameters
The method accepts the below parameters.
searchString
- It is the string to be searched for within the string
str.
position (optional)
- It is the index within
strto begin searching forsearchString. - The default value is 0.
Result
The method returns a true if searchString is found, otherwise returns false.
Example 1: Using the Method
The method searches for a specific string searchString in the string str and returns true if it is found, else returns false.
var str = "Learning JavaScript is fun!";
// Checks if the string contains the word "Java"
document.write(str.includes("Java")); // Prints: true
// Search is case sensitive
document.write(str.includes("java")); // Prints: false
// Search for blank
document.write(str.includes("")); // Prints: true
// Search for string not found
document.write(str.includes("hello")); // Prints: false
Output:
true
false
true
false
Example 2: Using the method with Position
The position parameter specifies the index within str to search for the searchString.
var str = "Learning JavaScript is fun!";
// Search for "Java" in a string from index 5
document.write(str.includes("Java", 5)); // Prints: true
// Search for "Java" in a string from index 10
document.write(str.includes("java", 10)); // Prints: false
Output:
true
false
Overall
The JavaScript method includes() checks if a string contains a specific string.