JavaScript includes() method
The includes()
method in JavaScript is used to determine whether a given string contains a specified substring (search string). It returns a boolean value (true
or false
) based on whether the substring is found within the string.
Syntax:
searchString
: The substring you want to search for within the string.position
(optional): The position in the string at which to begin the search. If omitted, the default is0
(the start of the string).
Return Value:
- It returns
true
if thesearchString
is found in the string; otherwise, it returnsfalse
.
Example 1: Basic Usage
In this example, the substring "world"
is found within the string "Hello, world!"
, so includes()
returns true
.
Example 2: Case Sensitivity
The includes()
method is case-sensitive. This means that "Hello"
and "hello"
are treated as different strings.
Example 3: Specifying the Starting Position
You can specify the position to start the search using the second parameter. The search begins at the specified index, and it does not search any earlier in the string.
Example 4: Using includes()
with Special Characters
The method works with strings that contain special characters, spaces, or punctuation.
Example 5: Strings That Do Not Contain the Substring
If the searchString
is not found in the original string, the method will return false
.
Example 6: Finding Empty Strings
The includes()
method will return true
if you search for an empty string, as every string contains an empty substring.
Summary:
- The
includes()
method checks if a string contains a specific substring and returnstrue
orfalse
. - It is case-sensitive and can accept a second argument to specify the starting position for the search.
- The method works with any character, including special characters and spaces.
- If you search for an empty string, it will always return
true
since every string contains an empty substring.