Home >Web Front-end >JS Tutorial >How to Efficiently Check for Substring Matches from an Array in JavaScript?

How to Efficiently Check for Substring Matches from an Array in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-31 09:03:29275browse

How to Efficiently Check for Substring Matches from an Array in JavaScript?

String Matching with Array Substrings in JavaScript

Problem: How to efficiently determine if a given string contains any substring from a predefined array in JavaScript?

Solution:

There are two approaches you can take for this task:

1. Array.some() Method:

The array.some() method allows you to check if at least one element in the array satisfies a given condition. You can utilize it as follows:

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

Or, with arrow functions and the includes() method:

<code class="javascript">if (substrings.some(v => str.includes(v))) {
  // There's at least one matching substring
}</code>

2. Regular Expression:

While there's no built-in function specifically designed for this type of search, you can construct a regular expression to match the desired substrings and use the test() method on the string. However, this approach can be computationally expensive for large arrays and strings.

<code class="javascript">const regex = new RegExp(`( ${substrings.join(' | ')} )`, 'g');
if (regex.test(str)) {
  // There's at least one matching substring
}</code>

Example:

Consider the following array of substrings and two different strings:

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

let str1 = "this has one";
let str2 = "this doesn't have any";</code>

Using the array.some() approach:

<code class="javascript">if (substrings.some(v => str1.includes(v))) {
  console.log(`Match using "${str1}"`);
} else {
  console.log(`No match using "${str1}"`);
}</code>

Output:

Match using "this has one"
<code class="javascript">if (substrings.some(v => str2.includes(v))) {
  console.log(`Match using "${str2}"`);
} else {
  console.log(`No match using "${str2}"`);
}</code>

Output:

No match using "this doesn't have any"

The above is the detailed content of How to Efficiently Check for Substring Matches 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