-2

If I have a number of characters (either as a string or an array), does JavaScript have a function to tell me if any of those characters appear within a string?

For example, given the following, I want a function that returns true because str does contain one of the characters in chars.

const chars = [ '[', ']', '{', '}' ];
var str = "BlahBlah}";

In C#, I can use IndexOfAny(), but I'm not finding a similar function in JavaScript.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
  • Yes, you can use the `includes()` method, nothing you have to loop over each char in the array and use the `includes` function on it. – Noubar K. Jul 01 '23 at 15:46
  • 1
    Does this answer your question? [How to check if a string contains text from an array of substrings in JavaScript?](https://stackoverflow.com/questions/5582574/how-to-check-if-a-string-contains-text-from-an-array-of-substrings-in-javascript) – pilchard Jul 01 '23 at 15:54
  • or [Check if a string contains any element of an array in JavaScript](https://stackoverflow.com/questions/37428338/check-if-a-string-contains-any-element-of-an-array-in-javascript) – pilchard Jul 01 '23 at 15:55
  • @pilchard: That isn't the same at all. – Jonathan Wood Jul 01 '23 at 15:56
  • 1
    It is identical and the 12 year old [accepted answer](https://stackoverflow.com/a/5582621/13762301) is the same as the one you accepted here `substrings.some(v => str.includes(v))` – pilchard Jul 01 '23 at 15:56

4 Answers4

1

Try this

const chars = [ '[', ']', '{', '}' ];
const str = "BlahBlah}";

const result = chars.some(x=>str.includes(x))

console.log(result)
Chris Barr
  • 29,851
  • 23
  • 95
  • 135
1

ES6 automates looping through arrays with Array.prototype.some().

Try:

substrings.some(function(v) { return str.indexOf(v) >= 0; })

Or, to prototype this to String yourself (not recommend):

String.prototype.indexOfAny = function(arr) {
    return arr.some(function(v) { return str.indexOf(v) >= 0; });
}
Makaze
  • 1,076
  • 7
  • 13
1

Reusable Functional Approach

const chars = [ '[', ']', '{', '}' ];
const str = "BlahBlah}";

const chars2 = [ '[', ']', '{', '}' ];
const str2 = "Amoos";


const findStringInArray = (string, array) => array.some( arr =>string.includes(arr) )


console.log( findStringInArray(str, chars) )



console.log( findStringInArray(str2, chars2) )
GMKHussain
  • 3,342
  • 1
  • 21
  • 19
0

JS contains metod includes. For example:

const chars = [ '[', ']', '{', '}' ];
var str = "BlahBlah}";

for (const i of str) {
  if (chars.includes(i)) {
    console.log(i);
  }
}
Sabir
  • 23
  • 5
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 03 '23 at 18:32