Home >Web Front-end >JS Tutorial >How to Find an Element in a JavaScript Array that Contains a Specific Substring?

How to Find an Element in a JavaScript Array that Contains a Specific Substring?

Barbara Streisand
Barbara StreisandOriginal
2024-11-01 13:24:02622browse

How to Find an Element in a JavaScript Array that Contains a Specific Substring?

How to Search an Array for a Partial String Match in JavaScript

Searching an array for a substring match can be a challenge, especially if the substring is only part of a larger string within the array elements. This guide will help you through the process, providing a simple and straightforward solution using JavaScript's native methods.

The Problem:

Given an array of strings and a substring to search for, you need to identify the array element that contains the substring and retrieve the substring component from that element.

The Solution:

The simplest and most efficient way to search an array for a substring match in JavaScript is to use the following code:

<code class="javascript">const array = ["item", "thing", "id-3-text", "class"];
const substring = "id-";

const result = array.findIndex(element => element.includes(substring));

if (result !== -1) {
  console.log(`Substring match found in element: ${array[result]}`);
} else {
  console.log("Substring match not found.");
}</code>

Understanding the Code:

  • findIndex(): This ES6 method iterates through the array and returns the index of the first element that matches the specified condition.
  • element: The parameter of the arrow function, which represents each element in the array.
  • includes(): This method checks if the element includes the specified substring.
  • If statement: If the substring is found, it prints the index of the matching element. If not, it prints "Substring match not found."

The above is the detailed content of How to Find an Element in a JavaScript Array that Contains a Specific Substring?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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