JavaScript .includes()方法的多个条件

时间:2016-06-18 11:37:41

标签: javascript methods

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

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

想象逗号状态"或" (它现在询问字符串是否包含hello hi 你好。所以只有一个,只有一个条件为真。

有没有这样做的方法?

10 个答案:

答案 0 :(得分:73)

您可以使用.some引用的some()方法。

  

// test cases var str1 = 'hi, how do you do?'; var str2 = 'regular string'; // does the test strings contains this terms? var conditions = ["hello", "hi", "howdy"]; // run the tests agains every element in the array var test1 = conditions.some(el => str1.includes(el)); var test2 = conditions.some(el => str2.includes(el)); // display results console.log(str1, ' ===> ', test1); console.log(str2, ' ===> ', test2);方法测试 数组中是否至少有一个元素   通过提供的函数实现的测试

{{1}}

答案 1 :(得分:13)

使用includes(),不,但您可以通过test()与REGEX实现相同的目标:

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

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

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

REGEX方法是一个更好的主意,因为它允许您将单词匹配为实际单词,而不是其他单词的子串。您只需要单词边界标记\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

答案 2 :(得分:13)

即使其中一个条件成立,也应该有效:

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

答案 3 :(得分:1)

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

要检查字符串中是否存在列表(数组)中单词的全部

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

答案 4 :(得分:1)

您还可以执行以下操作:

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

只要您的include中的任何一个返回true,则value将为true,否则它将为false。这与ES6完美配合。

答案 5 :(得分:0)

不是最好的答案,也不是最干净的答案,但是我认为这是更宽松的。 就像您要对所有检查使用相同的过滤器一样。 实际上,StrapiConfigs使用数组,并返回一个过滤后的数组(我也发现它更易于使用)。

.filter()

答案 6 :(得分:0)

这里有一个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

答案 7 :(得分:0)

另一个!

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 :(得分:-1)

扩展String本机原型:

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

答案 9 :(得分:-2)

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