lodash _.包含字符串中多个值之一 [英] lodash _.contains one of multiple values in string
问题描述
lodash中是否可以检查字符串是否包含数组中的值之一?
Is there a way in lodash to check if a strings contains one of the values from an array?
例如:
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
推荐答案
另一种解决方案可能比查找每个值更有效,可以根据这些值创建一个正则表达式.
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']));
限制
对于包含以下字符之一的值,此方法将失败:\ ^ $ * + ? . ( ) | { } [ ]
(它们是regex语法的一部分).
Limitation
This approach will fail for values containing one of the following characters: \ ^ $ * + ? . ( ) | { } [ ]
(they are part of the regex syntax).
如果可能的话,您可以使用以下功能(来自sindresorhus的 escape-string-regexp )以保护(转义)相关值:
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, "\\$&");
}
但是,如果需要为每个可能的values
调用它,则 String.prototype.includes
变得更有效率(请参阅@Andy和我的其他答案).
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).
这篇关于lodash _.包含字符串中多个值之一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!