multiple conditions for JavaScript .includes() method

user6234002 picture user6234002 · Jun 18, 2016 · Viewed 103.2k times · Source

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?

Answer

dinigo picture dinigo · Apr 25, 2017

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