FatDogMark FatDogMark - 5 months ago 7
Javascript Question

Concise way to compare against multiple values

Consider the following:

var a = 'jesus';

if(a == 'something' || a == 'nothing' || a=='anything' || a=='everything'){
alert('Who cares?');
}


Is there a way to make this shorter?

Is there anything in Javascript like
if (a=='bbb'||'ccc')
?

In addition, can jQuery help here?

Answer

With a regex:

if (/^(something|nothing|anything|everything)$/.exec('jesus')) alert('Who cares?');​

Or the opposite:

/^(something|nothing|anything|everything)$/.exec('jesus')||alert('Who cares?');​

[Update] Even shorter ;-)

if (/^(some|no|any|every)thing$/.exec('jesus')) alert('Who cares?');​
Comments