【问题标题】:multiple conditions for JavaScript .includes() methodJavaScript .includes() 方法的多个条件
【发布时间】:2020-07-25 06:35:38
【问题描述】:

只是想知道,有没有办法在 .includes 方法中添加多个条件,例如:

    var value = str.includes("hello", "hi", "howdy");

想象一下逗号状态“或”。

现在询问字符串是否包含 hello, hi howdy。所以只有一个,并且只有一个条件为真。

有没有办法做到这一点?

【问题讨论】:

  • or 意味着至少一个匹配就足够了。
  • 与其寻找包含方法的解决方案,不如尝试 indexOf 如下:['hello', 'hi', 'howdy'].indexOf(str)
  • @SkanderJenhani 在评论之前至少阅读并尝试。您的建议将始终返回-1
  • && 可以做什么?

标签: javascript methods


【解决方案1】:

使用includes(),不,但您可以通过test() 使用正则表达式实现相同的目的:

var value = /hello|hi|howdy/.test(str);

或者,如果这些词来自动态来源:

var words = ['hello', 'hi', 'howdy'];
var value = new RegExp(words.join('|')).test(str);

REGEX 方法是一个更好的主意,因为它允许您将单词匹配为实际单词,而不是 other 单词的子字符串。你只需要单词边界标记\b,所以:

var str = 'hilly';
var value = str.includes('hi'); //true, even though the word 'hi' isn't found
var value = /\bhi\b/.test(str); //false - 'hi' appears but not as its own word

【讨论】:

  • 如果单词包含特殊的正则表达式字符,这将不起作用。此外,这不会满足 OP 的明显要求,它仅在与 single 单词匹配时才匹配。
  • 嘿,Mitya,我写了这个受欢迎的答案,但我碰巧更喜欢你的解决方案。我已经尝试了很多次将结果限制为 只有一个 但不能弯曲正则表达式来做到这一点。 (hello|hi|howdy){1} 不工作。有什么想法吗?
  • 你到底是什么意思?如果您只想匹配一个,而不是多个,那么原始的includes() 肯定是您所需要的。
  • 我似乎找不到用单个正则表达式匹配“唯一一个”目的词的方法。也许你可以第一次匹配,然后计算 num 结果是否 == 1。不确定
  • REGEX 不是用于规定找到(或不找到)多少列入白名单的选项池的工具。它处理序列,所以你可能会在这里遇到困难。
【解决方案2】:

您可以使用引用here.some 方法。

some() 方法测试是否数组中至少有一个元素 通过提供的函数实现的测试

// test cases
const str1 = 'hi hello, how do you do?';
const str2 = 'regular string';
const str3 = 'hello there';

// do the test strings contain these terms?
const conditions = ["hello", "hi", "howdy"];

// run the tests against every element in the array
const test1 = conditions.some(el => str1.includes(el));
const test2 = conditions.some(el => str2.includes(el));
// strictly check that contains 1 and only one match
const test3 = conditions.reduce((a,c) => a + str3.includes(c), 0) == 1;

// display results
console.log(`Loose matching, 2 matches "${str1}" => ${test1}`);
console.log(`Loose matching, 0 matches "${str2}" => ${test2}`);
console.log(`Exact matching, 1 matches "${str3}" => ${test3}`);

此外,正如用户在下面提到的,匹配上面提到的“完全一致”的外观也很有趣(并且由 OP 要求)。这可以类似地计算与 .reduce 的交叉点并稍后检查它们是否等于 1。

【讨论】:

  • 注意点:some() 是一种方法,而不是运算符。否则,很好的答案。
  • 点了。谢谢
  • 只是为了强调任何更分心的人,事实上,正如答案中正确加粗的那样,这对于数组中有“至少一个元素”但不幸的是它没有回答 OP 的问题:“只有一个条件为真。”
  • 你是对的。添加了额外的条件来演示如何减少数组以检查有多少匹配项
【解决方案3】:

1 线解决方案:

String/Array.prototype.includes('hello' || 'hi' || 'howdy');

let words = 'cucumber, mercy, introduction, shot, howdy'
words.includes('hi' || 'howdy' || 'hello') // true
words.includes('hi' || 'hello') // false

【讨论】:

  • 因为'hi' 不是undefinedfalse,您提供的代码示例是检查words 字符串是否包含hi,因此words.includes(...) 语句都返回false。
【解决方案4】:

['hello', 'hi', 'howdy'].includes(str)怎么样?

【讨论】:

  • 不,它不起作用:['hello', 'hi', 'howdy'].includes('hello, how are you ?') 返回 false,而 OP 要求返回 true 的解决方案。
【解决方案5】:

扩展字符串原生原型:

if (!String.prototype.contains) {
    Object.defineProperty(String.prototype, 'contains', {
        value(patterns) {
            if (!Array.isArray(patterns)) {
                return false;
            }

            let value = 0;
            for (let i = 0; i < patterns.length; i++) {
                const pattern = patterns[i];
                value = value + this.includes(pattern);
            }
            return (value === 1);
        }
    });
}

允许您执行以下操作:

console.log('Hi, hope you like this option'.toLowerCase().contains(["hello", "hi", "howdy"])); // True

【讨论】:

    【解决方案6】:

    你也可以这样做:

    const str = "hi, there"
    
    const res = str.includes("hello") || str.includes("hi") || str.includes('howdy');
    
    console.log(res);

    只要你的其中一个包含返回 true,value 就会为 true,否则,它将为 false。这在 ES6 上运行得非常好。

    【讨论】:

    • OP 说,“所以只有一个,并且只有一个条件为真。”您的 sn-p 将为包含所有三个单词的字符串返回 true,而 OP 希望它返回 false。
    • 可以这样写:const res = str.includes("hello"|| "hi" || "howdy"); ?
    【解决方案7】:

    又一个!

    let result
    
    const givenStr = 'A, X' //values separated by comma or space.
    
    const allowed  = ['A', 'B']
    const given    = givenStr.split(/[\s,]+/).filter(v => v)
    
    console.log('given (array):', given)
    
    // given contains none or only allowed values:
    
    result = given.reduce((acc, val) => {
      return acc && allowed.includes(val)
    }, true)
    
    console.log('given contains none or only allowed values:', result)
    
    // given contains at least one allowed value:
    
    result = given.reduce((acc, val) => {
      return acc || allowed.includes(val)
    }, false)
    
    console.log('given contains at least one allowed value:', result)

    【讨论】:

      【解决方案8】:

      这可以通过使用 Array 和 RegEx 的 some/every 方法来完成。

      检查列表(数组)中的 ALL 个单词是否存在于字符串中:

      const multiSearchAnd = (text, searchWords) => (
        searchWords.every((el) => {
          return text.match(new RegExp(el,"i"))
        })
      )
      
      multiSearchAnd("Chelsey Dietrich Engineer 2018-12-11 Hire", ["cle", "hire"]) //returns false
      multiSearchAnd("Chelsey Dietrich Engineer 2018-12-11 Hire", ["che", "hire"]) //returns true
      

      检查列表(数组)中的 ANY 个单词是否存在于字符串中:

      const multiSearchOr = (text, searchWords) => (
        searchWords.some((el) => {
          return text.match(new RegExp(el,"i"))
        })
      )
      
      multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["che", "hire"]) //returns true
      multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["aaa", "hire"]) //returns true
      multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["che", "zzzz"]) //returns true
      multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["aaa", "1111"]) //returns false
      

      【讨论】:

      • 哇。这回答了我的两个问题。非常感谢!!!!
      【解决方案9】:

      这是一个controversial 选项:

      String.prototype.includesOneOf = function(arrayOfStrings) {
        if(!Array.isArray(arrayOfStrings)) {
          throw new Error('includesOneOf only accepts an array')
        }
        return arrayOfStrings.some(str => this.includes(str))
      }
      

      允许您执行以下操作:

      'Hi, hope you like this option'.toLowerCase().includesOneOf(["hello", "hi", "howdy"]) // True
      

      【讨论】:

        【解决方案10】:

        不是最好的答案,也不是最干净的,但我认为它更宽容。 就像您想对所有检查使用相同的过滤器一样。 实际上.filter() 使用数组并返回过滤后的数组(我也觉得更容易使用)。

        var str1 = 'hi, how do you do?';
        var str2 = 'regular string';
        var conditions = ["hello", "hi", "howdy"];
        
        // Solve the problem
        var res1 = [str1].filter(data => data.includes(conditions[0]) || data.includes(conditions[1]) || data.includes(conditions[2]));
        var res2 = [str2].filter(data => data.includes(conditions[0]) || data.includes(conditions[1]) || data.includes(conditions[2]));
        
        console.log(res1); // ["hi, how do you do?"]
        console.log(res2); // []
        
        
        // More useful in this case
        var text = [str1, str2, "hello world"];
        
        // Apply some filters on data
        var res3 = text.filter(data => data.includes(conditions[0]) && data.includes(conditions[2]));
        // You may use again the same filters for a different check
        var res4 = text.filter(data => data.includes(conditions[0]) || data.includes(conditions[1]));
        
        console.log(res3); // []
        console.log(res4); // ["hi, how do you do?", "hello world"]
        

        【讨论】:

          【解决方案11】:

          即使有一个条件也应该有效,并且只有一个条件为真:

          var str = "bonjour le monde vive le javascript";
          var arr = ['bonjour','europe', 'c++'];
          
          function contains(target, pattern){
              var value = 0;
              pattern.forEach(function(word){
                value = value + target.includes(word);
              });
              return (value === 1)
          }
          
          console.log(contains(str, arr));
          

          【讨论】:

          • 只是一个注释。任何在 Google Apps 脚本中尝试此操作的人都会收到 TypeError:stackoverflow.com/questions/51291776/…
          • 使用 indexOf('string') !== -1 而不是包含来避免这个错误
          猜你喜欢
          • 2012-08-14
          • 1970-01-01
          • 2013-12-08
          • 1970-01-01
          • 2023-01-27
          • 2017-08-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多