Possible Duplicate:
Javascript: The prettiest way to compare one value against multiple values
Javascript If statement used to check file extensions not working
In JS I’m trying to check whether an extension ends in “png” “jpg” or “gif”. I’m aware this can be done with a switch statement, but I’m wondering if there’s a simpler way to throw it all in the if conditional. Like:
if (aExtensions[i].toLowerCase() == ('jpg' || 'png' || 'gif')) {}
What’s the best way to achieve this?
You could use an array like this:
In this case, you store the “valid” extensions. Then, you can use the
indexOfmethod ofArrayto find if any of the items in the array match the specific extension you’re looking at – checking for a value that is0or greater.indexOfisn’t supported on older browsers, so you’d need to include a polyfill to back it up. There are several solutions for that.Of course, if you wanted to only use
ifstatements, you could use this format:Another possibility I can think of is a
switchstatement, like:I might as well include it (other answers had it first, definitely), but one more I can think of is using a regex, like:
But note that you will never be able to individually get the extensions back, and that’s why I would prefer one of the first two options I gave.