The includes() method is used to check whether a string contains a specific value. It returns a boolean result based on whether the text is found or not.
- Returns true if the string contains the specified value.
- Returns false if the value is not found.
- It is case-sensitive, so uppercase and lowercase letters are treated differently.
let text = "JavaScript is awesome";
let result = text.includes("awesome");
console.log(result);
Syntax:
string.includes(searchvalue, start)Parameters:
The includes() method accepts parameters that control how the search is performed. These parameters define what to search for and where to start searching.
- searchValue: The string that needs to be searched.
- start: The position from where the search begins.
- If start is not provided, the search starts from the beginning of the string.
Return Value:
The includes() method provides a simple true or false result. This result tells whether the given value exists in the string.
- Returns true if the value is present.
- Returns false if the value is not found.
Example 1: The code checks whether "Geeks" exists in "Welcome to GeeksforGeeks." and logs true because the substring is found.
let str = "Welcome to GeeksforGeeks.";
let check = str.includes("Geeks");
console.log(check);
Output
true
Example 2: Here, the second parameter is not provided, so the search starts from index 0. Since the method is case-sensitive, it treats the strings differently and therefore returns false.
let str = "Welcome to GeeksforGeeks.";
let check = str.includes("geeks");
console.log(check);
Example 3: The code checks whether the character "o" exists in "Welcome to GeeksforGeeks." starting from index 17 and logs false, since "o" does not appear after that index.
let str = "Welcome to GeeksforGeeks.";
let check = str.includes("o", 17);
console.log(check);
Example 4: If the computed index (starting index) i.e. the position from which the search will begin is less than 0, the entire array will be searched.
let str = "Welcome to GeeksforGeeks.";
let check = str.includes("o", -2);
console.log(check);