OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Determine if string is in list in JavaScript

  • Thread starter Thread starter ErikE
  • Start date Start date
E

ErikE

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

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

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

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

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

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

Or one could use the switch function:

Code:
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.

<p>In SQL we can see if a string is in a list like so:</p>

<pre><code>Column IN ('a', 'b', 'c')
</code></pre>

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

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

<p>And I'm not sure about the performance or clarity of this:</p>

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

<p>Or one could use the switch function:</p>

<pre><code>var str = 'a',
flag = false;

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

if (expression1 || expression2 || flag) {
// do something
}
</code></pre>

<p>But that is a horrible mess. Any ideas?</p>

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