Подтвердить что ты не робот

Lodash _. содержит одно из нескольких значений в строке

Есть ли способ в lodash проверить, содержит ли строки одно из значений из массива?

Например:

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
4b9b3361

Ответ 1

Другим решением, возможно более эффективным, чем поиск любых значений, может быть создание регулярного выражения из значений.

При повторении всех возможных значений будет подразумеваться множественный анализ текста, с регулярным выражением, достаточно только одного.

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

Ответ 2

Используйте _.some и _.includes:

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

DEMO

Ответ 3

Нет. Но это легко реализовать с помощью String.includes. Вам не нужен lodash.

Вот простая функция, которая выполняет только это:

function multiIncludes(text, values){
  return values.some(function(val){
    return text.includes(val);
  });
}

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