Home >Web Front-end >JS Tutorial >How to Efficiently Check for Substring Matches from an Array 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:
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>
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>
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!