Determine if string is in list in JavaScript

ErikE picture ErikE · Mar 12, 2010 · Viewed 338.7k times · Source

In SQL we can see if a string is in a list like so:

Column IN ('a', 'b', 'c')

What's a good way to do this in JavaScript? It's so clunky to do this:

if (expression1 || expression2 || str === 'a' || str === 'b' || str === 'c') {
   // do something
}

And I'm not sure about the performance or clarity of this:

if (expression1 || expression2 || {a:1, b:1, c:1}[str]) {
   // do something
}

Or one could use the switch function:

var str = 'a',
   flag = false;

switch (str) {
   case 'a':
   case 'b':
   case 'c':
      flag = true;
   default:
}

if (expression1 || expression2 || flag) {
   // do something
}

But that is a horrible mess. Any ideas?

In this case, I have to use Internet Explorer 7 as it's for a corporate intranet page. So ['a', 'b', 'c'].indexOf(str) !== -1 won't work natively without some syntax sugar.

Answer

SLaks picture SLaks · Mar 12, 2010

You can call indexOf:

if (['a', 'b', 'c'].indexOf(str) >= 0) {
    //do something
}