-2

instead of doing something like:

 if( myString.includes("book")||myString.includes("red")||myString.includes("pen")){
    ...
  }

I need something like:

 if( myString.includesAnyOf("book","red","pen")){
    ...
  }

a pure Js or a Lodash solution would work for me.

  • 1
    Does this answer your question? [Check variable equality against a list of values](https://stackoverflow.com/questions/4728144/check-variable-equality-against-a-list-of-values) – VLAZ Jul 13 '20 at 19:06
  • what about using regex? – Dominik Matis Jul 13 '20 at 19:06
  • You can refer this https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-a-value-in-javascript – Mayank Soni Jul 13 '20 at 19:07
  • Does this answer your question? [How do I check if an array includes a value in JavaScript?](https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-a-value-in-javascript) – Mayank Soni Jul 13 '20 at 19:09
  • yeah, using `includes` with array of values is more preferable here – Dominik Matis Jul 13 '20 at 19:09

4 Answers4

2

Simple regular expression with test

var words = /(book|red|pen)/;
console.log(words.test("I use a pen."));
console.log(words.test("I use a red hen."));
console.log(words.test("I use a blue book."));
console.log(words.test("I use a hen."));
console.log(words.test("I use an open door."));

If you want to do string method it is Array some and String includes.

var words = ["book","red","pen"];

const checkString = str =>
  words.some(word => str.includes(word));
  
  
console.log(checkString("I use a pen."));
console.log(checkString("I use a red hen."));
console.log(checkString("I use a blue book."));
console.log(checkString("I use a hen."));
console.log(checkString("I use an open door."));
epascarello
  • 204,599
  • 20
  • 195
  • 236
1
["book","red","pen"].some(ele => string.includes(ele));

function stringCheck(string){
  return ["book","red","pen"].some(ele => string.includes(ele));
}

console.log(stringCheck("testing for words"));
console.log(stringCheck("what if I use book?"));
Pavlos Karalis
  • 2,893
  • 1
  • 6
  • 14
0

You can use filter

["book","red","pen"].filter(value => myString.includes(value))
Omar Sy
  • 486
  • 2
  • 8
0

There's nothing built-in that will do that for you, you'll have to write a function for it or use this one liner that takes the map function for advantage:

substringsArray.some(substring=>yourBigString.includes(substring))

if you're looking for a more readable solution, then looping through an array would suffice.

const yourstring = 'some string'; // the string to check against
const substrings = ['foo','bar']; // search keys

while(substrings.length--) {
   if(yourstring.indexOf(substrings[length])!=-1) {
       // one of the substrings is in yourstring
   }
}
PatricNox
  • 3,306
  • 1
  • 17
  • 25