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
One line solution
Returns
true\false
if substringexists\does'nt exist
Needs ES6 support
Javascript function to search an array of tags or keywords using a search string or an array of search strings. (Uses ES5 some array method and ES6 arrow functions)
Example usage:
This is super late, but I just ran into this problem. In my own project I used the following to check if a string was in an array:
This way you can take a predefined array and check if it contains a string:
Drawing from T.J. Crowder's solution, I created a prototype to deal with this problem:
edit: If the order of the tests doesn't matter, you could use this (with only one loop variable):
If the array is not large, you could just loop and check the string against each substring individually using
indexOf()
. Alternatively you could construct a regular expression with substrings as alternatives, which may or may not be more efficient.