Pretty straight forward. In javascript, I need to check if a string contains any substrings held in an array.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- how to split a list into a given number of sub-lis
For people Googling,
The solid answer should be.
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:
...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.Gratuitous live example
Update:
In a comment on the question, Martin asks about the new
Array#map
function in ECMAScript5.map
isn't all that much help, butsome
is:Live example (Only works on modern browsers)
Mind you, it does mean some overhead, and you only have it on ECMAScript5-compliant implementations (so, not IE7 or earlier, for instance; maybe not even IE8), but still if you're really into that style of programming... (And you could use an ECMAScript5 shim, this one or any of several others.)
building on T.J Crowder's answer
using escaped RegExp to test for "at least once" occurrence, of at least one of the substrings.
Using underscore.js or lodash.js, you can do the following on an array of strings:
And on a single string: