lodash _.contains one of multiple values in string

柔情痞子 提交于 2019-12-21 07:42:39

问题


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

回答1:


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).




回答2:


Use _.some and _.includes:

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

DEMO




回答3:


No. But this is easy to implement using String.includes. You don't need lodash.

Here is a simple function that does just this:

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


来源:https://stackoverflow.com/questions/37023066/lodash-contains-one-of-multiple-values-in-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!