【问题标题】:lodash _.contains one of multiple values in stringlodash _.contains 字符串中的多个值之一
【发布时间】:2023-04-03 10:06:01
【问题描述】:

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

【问题讨论】:

  • 不用lodash values.some(el => text.indexOf(el) > -1) btw 也可以轻松完成。

标签: javascript lodash


【解决方案1】:

使用_.some_.includes

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

DEMO

【讨论】:

    【解决方案2】:

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

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

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

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

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

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

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

    【讨论】:

    • 是的,我认为使用正则表达式是最好的选择。
    • LOL yeaaahhhh 正则表达式....伙计们,在你之后必须有人支持你的地狱。
    【解决方案3】:

    没有。但这很容易使用String.includes 实现。 You don't need 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']));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-25
      • 1970-01-01
      • 1970-01-01
      • 2011-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多