Concise way to compare against multiple values
You could use this...
if (["something", "nothing", "anything", "everything"].includes(a)) {
alert('Who cares?');
}
If you're stuck with older browser support...
if (["something", "nothing", "anything", "everything"].indexOf(a) > -1) {
alert('Who cares?');
}
You also tagged it jQuery, so if you need to support older browsers without Array.prototype.indexOf()
, you could use $.inArray()
.
You can put the options in array and use jQuery $.inArray()
or javascrpt indexOf()
to search array
Pure javascript
Live Demo
var a = 'anything';
arr = ['something', 'nothing', 'anything', 'everything'];
if(arr.indexOf(a) != -1)
alert("condition met");
else
alert("condition not met");
With jQuery
Live Demo
var a = 'jesus';
arr = ['something', 'nothing', 'anything', 'everything'];
if($.inArray(a, arr) != -1) // With jQuery
alert("condition met");
else
alert("condition not met");
With ES7 you are able to use Array.prototype.includes and even shorter notation than indexOf, which is already implemented in every modern browser.
Here is the example usage:
if (['hero', 'anything', 'everything'].includes(me)) {
alert('Who cares?');
}
And the polyfill from Mozilla.
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?');