Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Just wondering, is there a way to add multiple conditions to a .includes method, for example:

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

Imagine the comma states "or".

It's asking now if the string contains hello, hi or howdy. So only if one, and only one of the conditions is true.

Is there a method of doing that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
911 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use the .some method referenced here.

The some() method tests whether at least one element in the array passes the test implemented by the provided function.

// 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}`);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...