The includes() method of the String class in JavaScript determines whether the calling string contains the characters of a specified string, searchString. An optional parameter, position, can specify the position within the string at which to begin the search.
There are 2 variations for the syntax of String.includes() method. They are:
includes(searchString)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
searchString | required | The characters to be searched for within this string. |
This method determines whether the calling string contains searchString.
Returns value of type Boolean
.
includes(searchString, position)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
searchString | required | The characters to be searched for within this string. |
position | optional | The position within the string at which to begin the search. Defaults to 0. |
This method determines whether the calling string contains searchString, starting the search at the specified position.
Returns value of type Boolean
.
In JavaScript, we can use the includes()
method to check if a string contains a specified substring.
For example,
str
with the value 'Hello, world!'
.includes()
method with the argument 'world'
to check if the string contains 'world'
.result
.result
to the console using the console.log()
method.const str = 'Hello, world!';
const result = str.includes('world');
console.log(result);
true
In JavaScript, we can use the includes()
method to check if a string contains a specified substring, starting from a given position.
For example,
str
with the value 'Hello, world!'
.includes()
method with the arguments 'Hello'
and 5
to check if the substring from position 5
contains 'Hello'
.result
.result
to the console using the console.log()
method.const str = 'Hello, world!';
const result = str.includes('Hello', 5);
console.log(result);
false
In JavaScript, we can use the includes()
method to check if a string does not contain a specified substring.
For example,
str
with the value 'Hello, world!'
.includes()
method with the argument 'JavaScript'
to check if the string contains 'JavaScript'
.result
.result
to the console using the console.log()
method.const str = 'Hello, world!';
const result = str.includes('JavaScript');
console.log(result);
false
In this JavaScript tutorial, we learned about includes() method of String: the syntax and few working examples with output and detailed explanation for each example.