Home >Web Front-end >JS Tutorial >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:
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!