Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 591
yeouuu Avatar asked May 04 '16 09:05

yeouuu


2 Answers

Use _.some and _.includes:

var text = 'this is some sample text';
var values = ['sample', 'anything'];

console.log(_.some(values, (el) => _.includes(text, el)));

var values = ['no', 'nope'];

console.log(_.some(values, (el) => _.includes(text, el)));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

The more modern approach would be to use native JS to achieve the same thing without the need for an external library.

const text = 'this is some sample text';
const values1 = ['sample', 'anything'];
const values2 = ['no', 'nope'];

function test(text, arr) {
  return arr.some(el => {
    return text.includes(el);
  });
}

console.log(test(text, values1));
console.log(test(text, values2));
like image 54
Andy Avatar answered Nov 11 '22 13:11

Andy


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.

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']));

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:

function escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

However, if you need to call it for every possible values, it is possible that a combination of Array.prototype.some and String.prototype.includes becomes more efficient (see @Andy and my other answer).

like image 5
Quentin Roy Avatar answered Nov 11 '22 15:11

Quentin Roy