Is there a way in lodash to check if a strings contains one of the values from an array?
For example:
var text = 'this is some sample text';
var values = ['sample', 'anything'];
_.contains(text, values); // should be true
var values = ['nope', 'no'];
_.contains(text, values); // should be false
Use
_.some
and_.includes
:DEMO
Another solution, probably more efficient than looking for every values, can be to create a regular expression from the values.
While iterating through each possible values will imply multiple parsing of the text, with a regular expression, only one is sufficient.
Limitation This approach will fail for values containing one of the following characters:
\ ^ $ * + ? . ( ) | { } [ ]
(they are part of the regex syntax).If this is a possibility, you can use the following function (from sindresorhus's escape-string-regexp) to protect (escape) the relevant values:
However, if you need to call it for every possible
values
, it is possible that a combination ofArray.prototype.some
andString.prototype.includes
becomes more efficient (see @Andy and my other answer).No. But this is easy to implement using String.includes. You don't need lodash.
Here is a simple function that does just this: