Determine if string has at least 2 same elements from an array

You can use Array#some and String#split to do it:

const check=(array,string)=>array.some(char=>(string.split(char).length-1)>=2)

const array = ["!", "?"];

console.log(check(array,"!hello"))
console.log(check(array,"!hello?"))
console.log(check(array,"!hello!"))
console.log(check(array,"hello ??"))
console.log(check(array,"hello ?test? foo"))
console.log(check(array, "hello ?test ?? foo"))

How does it work?

Let's split up (I mean to split() up)!

const check=(array,string)=>
  array.some(char=>
    (
      string.split(char)
      .length-1
    )>=2
  )
  • First, use Array#some, which tests that at least one element of the array should pass (i.e. either ? or !)
  • Split up the string by char, and count how many parts do we have
    • If we have n parts, it means that we have n-1 places where the char matches. (e.g. 2 | splits a string into 3 parts: a|b|c)
  • Finally, test whether we have 2 or more delimiters

Another way is to use a pattern with a capturing group and a dynamically created character class for [!?] and a backreference \1 to what is captured in group 1 to make sure there are 2 of the same characters present.

([!?]).*\1

Regex demo

For example

const array = ["!", "?"];
const regex = new RegExp("([" + array.join(("")) + "]).*\\1");
[
  "!hello",
  "!hello?",
  "!hello!",
  "hello ??",
  "hello ?test? foo",
  "hello ?test ?? foo"
].forEach(str => console.log(str + ": " + regex.test(str)));