Home  >  Article  >  Web Front-end  >  How to Check if a String Contains Any of the Substrings from an Array in JavaScript?

How to Check if a String Contains Any of the Substrings from an Array in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-11-01 04:59:02162browse

How to Check if a String Contains Any of the Substrings from an Array in JavaScript?

Finding Substrings in a String with JavaScript Arrays

To determine if a string contains any of the substrings from an array, JavaScript provides flexible approaches.

Array Some Method

The some method iterates over an array, providing a callback function to test each element. To check for substrings, use the indexOf() method to search for each array element within the string:

<code class="js">if (substrings.some(function(v) { return str.indexOf(v) >= 0; })) {
    // There's at least one substring match
}</code>

Regular Expression

Regular expressions offer a powerful way to match text patterns. To search for any substring in the array within the string, create a regex with all substrings as alternate options and use the test() method:

<code class="js">const regex = new RegExp(substrings.join("|"));
if (regex.test(str)) {
    // At least one substring matches
}</code>

Example

Let's consider an array of substrings:

<code class="js">const substrings = ["one", "two", "three"];</code>

String with Substring Match

<code class="js">const str = "This string includes \"one\".";

// Using array some method
const someMethodMatch = substrings.some(v => str.includes(v));

// Using regular expression
const regexMatch = str.match(new RegExp(substrings.join("|")));</code>

String without Substring Match

<code class="js">const str = "This string doesn't have any substrings.";

// Using array some method
const someMethodNoMatch = substrings.some(v => str.includes(v));

// Using regular expression
const regexNoMatch = str.match(new RegExp(substrings.join("|")));</code>

Results

Test Method String with Match String without Match
Array some someMethodMatch = true someMethodNoMatch = false
Regular expression regexMatch = true regexNoMatch = null

The above is the detailed content of How to Check if a String Contains Any of the Substrings from an Array in JavaScript?. 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