How to check if a string contains text from an array of substrings in JavaScript? How to check if a string contains text from an array of substrings in JavaScript? arrays arrays

How to check if a string contains text from an array of substrings in JavaScript?


There's nothing built-in that will do that for you, you'll have to write a function for it.

If you know the strings don't contain any of the characters that are special in regular expressions, then you can cheat a bit, like this:

if (new RegExp(substrings.join("|")).test(string)) {    // At least one match}

...which creates a regular expression that's a series of alternations for the substrings you're looking for (e.g., one|two) and tests to see if there are matches for any of them, but if any of the substrings contains any characters that are special in regexes (*, [, etc.), you'd have to escape them first and you're better off just doing the boring loop instead. For info about escaping them, see this question's answers.

Live Example: