0

Is there a way to test for occurrence of specific characters in a more elegant way using Javascript syntax but without RegEx? Trying to avoid repetitive 'or' conditions if possible.

if (target == "+" || target == "-" || target == "*" || target == "/") {
    alert("hit a function");
}

Thanks.

0stone0
  • 34,288
  • 4
  • 39
  • 64
  • 1
    Make it an array and check with `includes`: `if ([ '+', '-', '*', '/' ].includes(target))` – 0stone0 Apr 12 '22 at 15:19
  • if (target.includes("+", "-", "*", "/")) ?? may work? – Jamie Garcia Apr 12 '22 at 15:20
  • Weirdly Jamie that tested true for the first character only (+) - ignoring the others. I then swapped the chars, and again it only proved true for the initial entry. Thanks 0stone0. – malkit benning Apr 12 '22 at 15:30
  • Thanks 0stone0, I've added your code, and yes it does indeed work. I would give you an upvote, but I'm so new I don't think I can. Your help however is much appreciated. – malkit benning Apr 12 '22 at 15:33

1 Answers1

0

There are a couple of ways of doing this:

  1. Use an array and includes: ['+', '-', '*', '/'].includes(target)
  2. Use an object with keys your values and check for that
 const values = { '*': true, '-': true, '+': true, '/': true}
 if (values[target] === true)

But writing a long boolean condition could also work. Just wrap that in a function so you don't have to c/p code around

Radu Diță
  • 13,476
  • 2
  • 30
  • 34