JavaScript String includes() Method
Last Updated :
05 Mar, 2024
The includes()
method in JavaScript is used to determine whether a string contains another string within it. It returns true
if the specified string is found, and false
otherwise.
Note: The includes() method is case sensitive i.e. it will treat the Uppercase Characters and Lowercase Characters differently.
String includes() Method Syntax
string.includes(searchvalue, start)
String includes() Method Parameters
- search value: It is the string in which the search will take place.
- start: This is the position from where the search will be processed
(although this parameter is not necessary if this is not mentioned the search will begin from the start of the string).
String includes() Method Return Value
Returns either a Boolean true indicating the presence or it returns a false indicating the absence.
String includes() Method Example
Example 1: Checking if string is present in another string
The code checks if the string “Geeks” is present in the string “Welcome to GeeksforGeeks.”. It then logs the result, which is true
, since “Geeks” is indeed present in the string.
javascript
let str = "Welcome to GeeksforGeeks." ;
let check = str.includes( "Geeks" );
console.log(check);
|
Example 2: Checking for Case-Sensitive String
Here, the second parameter is not defined, so the search will take place from the starting index. But as this method is case sensitive it will treat the two strings differently, hence returning a boolean false.
javascript
let str = "Welcome to GeeksforGeeks." ;
let check = str.includes( "geeks" );
console.log(check);
|
Example 3: Checking for a string at particular Index
The code checks if the character “o” is present in the string “Welcome to GeeksforGeeks.” starting from index 17. It then logs the result, which is false
, since “o” is not present in the substring starting from index 17.
javascript
let str = "Welcome to GeeksforGeeks." ;
let check = str.includes( "o" , 17);
console.log(check);
|
Example 4: Negative start Index
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.
javascript
let str = "Welcome to GeeksforGeeks." ;
let check = str.includes( "o" , -2);
console.log(check);
|
Supported Browsers:
Share your thoughts in the comments
Please Login to comment...