lodash _.contains string中的多个值之一

yeo*_*uuu 13 javascript 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
Run Code Online (Sandbox Code Playgroud)

And*_*ndy 27

使用_.some_.includes:

_.some(values, (el) => _.includes(text, el));
Run Code Online (Sandbox Code Playgroud)

DEMO


Que*_*Roy 5

另一种可能比查找每个值更有效的解决方案是从这些值创建一个正则表达式。

虽然迭代每个可能的值意味着对文本进行多次解析,但使用正则表达式,只有一个就足够了。

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']));
Run Code Online (Sandbox Code Playgroud)

限制 对于包含以下字符之一的值,此方法将失败:(\ ^ $ * + ? . ( ) | { } [ ]它们是正则表达式语法的一部分)。

如果这是可能的,您可以使用以下函数(来自 sindresorhus 的escape-string-regexp)来保护(转义)相关值:

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

但是,如果您需要为每一种可能的情况调用它values,则Array.prototype.some和的组合可能String.prototype.includes会变得更有效(请参阅@Andy 和我的其他答案)。

  • LOL yeaaahhhh regexps .... 伙计们,有人会在你之后支持你的地狱。 (4认同)