FatDogMark FatDogMark - 1 year ago 75
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 Source

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?');​
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download