只是想知道,是否有一种方法可以向.includes方法添加多个条件,例如:

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

想象一下逗号表示“或”。

它现在询问字符串是否包含hello, hi或howdy。所以只有当其中一个条件为真。

有什么方法可以做到吗?


当前回答

您可以使用这里引用的.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。

其他回答

你也可以这样做:

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

只要其中一个include返回真值,value就为真,否则,它就为假。这在ES6中工作得非常好。

这可以通过使用Array和RegEx的一些/每个方法来完成。

检查list(array)中的所有单词是否存在于字符串中:

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

检查list(array)中的任何单词是否存在于字符串中:

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

这取决于你在什么上下文中使用它。 我在一个对象上使用它来检查是否有任何键有一个空字符串或null作为它的值,它工作

Object.values(object).includes('' || null)

另一个!

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)

那么['hello', 'hi', 'howdy'].includes(str)呢?