Home > Web Front-end > JS Tutorial > body text

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

Susan Sarandon
Release: 2024-11-01 04:59:02
Original
156 people have browsed it

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

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

Example

Let's consider an array of substrings:

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

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!