Pretty straight forward. In javascript, I need to check if a string contains any substrings held in an array.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There’s nothing built-in that will do that for you, you’ll have to write a function for it, although it can be just a callback to the
somearray method.Two approaches for you:
somemethodArray
someThe array
somemethod (added in ES5) makes this quite straightforward:Even better with an arrow function and the newish
includesmethod (both ES2015+):Live Example:
Regular expression
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:
…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: