Home > Web Front-end > JS Tutorial > How to use includes in js

How to use includes in js

下次还敢
Release: 2024-05-01 04:24:14
Original
745 people have browsed it

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.

How to use includes in js

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template