0

I am checking if a variable matches with any of the following strings:

if (re == "Neliöhinta"||re == "Yhtiövastike"||re == "Vesimaksu"||re == "Hoitovastike"||re == "Rahoitusvastike") {
  //do something
}

I was wondering, is there a more elegant/shorter way to write this if condition? Something along the lines of

if(re == ("Neliöhinta"||"Yhtiövastike"||"Vesimaksu"||"Hoitovastike"||"Rahoitusvastike")) 

(which doesn't work)

Best I have found so far is

if(/Neliöhinta|Yhtiövastike|Vesimaksu|Hoitovastike|Rahoitusvastike/g.test(field))

Any other ways to do this? Cheers

jlo
  • 2,157
  • 2
  • 17
  • 23
  • For a long list, `Array#includes` is the modern way (or `Array#some` if the elements are non primitives). `Array#findIndex` would be commonly used in ES5. – Ben Aston May 14 '20 at 11:21

1 Answers1

4

You could use an array instead:

const permittedWords = ["Neliöhinta", "Yhtiövastike", "Vesimaksu", "Hoitovastike", "Rahoitusvastike"];
if (permittedWords.includes(re)) {
  // do something
}

Your current technique won't work perfectly, because it'll also match strings which include the word but don't exactly match it, eg aaaaNeliöhinta. To fix the regular expression, anchor it to the beginning and end of the string with ^ and $, and remove the global flag:

if(/^(?:Neliöhinta|Yhtiövastike|Vesimaksu|Hoitovastike|Rahoitusvastike)$/.test(field))
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320