Checking if a string includes a specific substring
String includes: String.includes()
The includes() method in JavaScript is used to determine whether one string can be found within another string. This method returns true if the specified string is found, and false otherwise.
Syntax:
The parameters
- searchString: The string to search for within the original string;
- position(optional): The position within the original string at which to begin searching for the searchString. It is an optional parameter, and if not specified, the search starts from the beginning of the string.
Return Value:
The includes()
method returns a boolean value:
- returns
true
if the searchString is found within the original string. - returns
false
if the searchString is not found.
Example
In this example, the includes()
method is used to check if the string 'world'
is present in the original string str. The first console.log statement outputs true
because 'world'
is found in the string. The second console.log
statement outputs false
as 'universe'
is not present.
In the example above, the includes()
method is called with both the searchString
('world'
) and the position
(7
) parameters. The position parameter specifies the index at which the search should begin. The console.log statement outputs false
because, starting from index 7, the 'world'
string is not found in the remaining portion of the string.
The position parameter is 0-index. For example for indicating the first character of the string you need to use the value 0 as position.
By using the String.includes()
method, you can efficiently determine whether a particular substring exists within a given string, providing a convenient way to handle string containment checks in JavaScript applications.