Home >Web Front-end >JS Tutorial >How to use includes in js
The includes() method in JavaScript is used to check whether an array or string contains a specific element or substring. It starts the search at a specific position in the string or array, depending on the specified start argument. Returns true if found; false if not found.
Usage of includes() in JavaScript
What is includes()?
includes() is a built-in method in JavaScript that is used to determine whether a string or array contains a given substring or element.
Syntax
<code class="javascript">array.includes(element, start) string.includes(substring, start)</code>
Where:
array
or string
: to be checked Array or string. element
or substring
: The element or substring to be found. start
(optional): Specify the position in the string or array to start searching (starting from 0). Usage
Array
To check whether an array contains an element, you can use the following syntax:
<code class="javascript">const fruits = ["apple", "banana", "orange"]; console.log(fruits.includes("apple")); // true console.log(fruits.includes("grape")); // false</code>
String
To check whether a string contains a certain substring, you can use the following syntax:
<code class="javascript">const message = "Hello, world!"; console.log(message.includes("world")); // true console.log(message.includes("universe")); // false</code>
Optional The start
Parameters The
start
parameter allows you to specify where in a string or array to start searching. For example:
<code class="javascript">const fruits = ["apple", "banana", "orange", "apple"]; console.log(fruits.includes("apple", 2)); // true (从索引 2 开始查找) console.log(message.includes("world", 6)); // false (从索引 6 开始查找)</code>
Return result
includes() method returns a Boolean value:
true
: If The specified element or substring was found. false
: If the specified element or substring cannot be found. The above is the detailed content of How to use includes in js. For more information, please follow other related articles on the PHP Chinese website!