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


101

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

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

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

现在询问字符串是否包含hello,hihowdy。因此,只有在其中一个条件为真的情况下。

有没有这样做的方法?


1
or意味着至少一场比赛就足够了。
robertklep

1
您可以尝试像这样尝试indexOf而不是使用include方法寻找解决方案: ['hello', 'hi', 'howdy'].indexOf(str)
Skander Jenhani

@SkanderJenhani至少阅读并尝试后再发表评论。您的建议将永远返回-1
chankruze

2
可以做&&什么?
arora

Answers:


30

即使只有一个条件为真,这也应该起作用:

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

请注意。:任何人在谷歌Apps脚本尝试,这将得到一个类型错误stackoverflow.com/questions/51291776/...
库尔特利德利

207

您可以使用此处.some引用的方法。

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

// test cases
var str1 = 'hi, how do you do?';
var str2 = 'regular string';

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

// run the tests against 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);


3
注意事项:some()是一种方法,而不是运算符。否则,很好的答案。
Mitya '18年

点了。谢谢
dinigo '18

26

使用includes(),不,但是您可以通过REGEX通过test()以下方法实现相同的目的:

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

如果单词包含特殊的正则表达式字符,则此方法将无效。此外,这将无法满足OP的明显要求,仅当存在单个单词匹配时才匹配。

17

您也可以这样做:

const str = "hi, there"

const res = str.includes("hello") || str.includes("hi") || str.includes('howdy');

console.log(res);

每当您的包含之一返回true时,value就会为true,否则它将为false。这与ES6完美配合。


OP说:“因此,只有其中一个条件成立,并且只有其中一个条件成立。” 对于包含所有三个单词的字符串,您的代码段将返回true,而OP希望它返回false。
Dane Brouwer

4

这可以通过使用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

哇。这回答了我两个问题。非常感谢!!!
BoundForGlory

2

不是最好的答案,也不是最干净的答案,但我认为这是更宽松的。就像您要对所有检查使用相同的过滤器一样。实际.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"]

2

这是一个有争议的选项:

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

1

另一个!

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)


-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

-2

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


1
不,它不起作用:['hello', 'hi', 'howdy'].includes('hello, how are you ?')return false,而OP要求返回的解决方案true
巴吉
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.