"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-11-06
Browse:788

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:

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

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:

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

Example

Let's consider an array of substrings:

const substrings = ["one", "two", "three"];

String with Substring Match

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("|")));

String without Substring Match

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("|")));

Results

Test MethodString with MatchString without Match
Array somesomeMethodMatch = truesomeMethodNoMatch = false
Regular expressionregexMatch = trueregexNoMatch = null
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3