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:
In a comment on the question, Martin asks about the new Array.prototype.map
method in ECMAScript5. map
isn't all that much help, but some
is:
if (substrings.some(function(v) { return str.indexOf(v) >= 0; })) { // There's at least one}
Live Example:
You only have it on ECMAScript5-compliant implementations, though it's trivial to polyfill.
Update in 2020: The some
example can be simpler with an arrow function (ES2015+), and you might use includes
rather than indexOf
:
if (substrings.some(v => str.includes(v))) { // There's at least one}
Live Example:
Or even throw bind
at it, although for me the arrow function is much more readable:
if (substrings.some(str.includes.bind(str))) { // There's at least one}
Live Example:
One line solution
substringsArray.some(substring=>yourBigString.includes(substring))
Returns true\false
if substring exists\does'nt exist
Needs ES6 support
var yourstring = 'tasty food'; // the string to check againstvar substrings = ['foo','bar'], length = substrings.length;while(length--) { if (yourstring.indexOf(substrings[length])!=-1) { // one of the substrings is in yourstring }}