Javascript lodash _.包含字符串中的多个值之一
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37023066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
lodash _.contains one of multiple values in string
提问by yeouuu
Is there a way in lodash to check if a strings contains one of the values from an array?
lodash 有没有办法检查字符串是否包含数组中的一个值?
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
采纳答案by Quentin Roy
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']));
LimitationThis 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:
如果这是可能的,您可以使用以下函数(来自 sindresorhus 的escape-string-regexp)来保护(转义)相关值:
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).
但是,如果您需要为每一种可能的情况调用它values
,则Array.prototype.some
和的组合可能String.prototype.includes
会变得更有效(请参阅@Andy 和我的其他答案)。
回答by Andy
回答by Quentin Roy
No. But this is easy to implement using String.includes. You don't need lodash.
不。但是使用String.includes很容易实现。你不需要 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']));