yeouuu yeouuu - 6 months ago 104
Javascript Question

lodash _.contains one of multiple values in string

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

Answer

Another solution, probably more efficient than looking for every values, can be to create a regular expression from the values.

It is also shorter.

function multiIncludes(text, values){
  var re = new RegExp(values.join('|'));
  return re.test(text);
}

document.write(multiIncludes('this is some sample text',
                             ['sample', 'anything']));
document.write('<br />');
document.write(multiIncludes('this is some sample text',
                             ['nope', 'anything']));

Comments