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:
var extensions = ["jpg", "png", "gif"];
if (extensions.indexOf(aExtensions[i].toLowerCase()) > -1) {
// match
}
In this case, you store the "valid" extensions. Then, you can use the indexOf
method of Array
to find if any of the items in the array match the specific extension you're looking at - checking for a value that is 0
or greater.
indexOf
isn'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 if
statements, you could use this format:
var ext = aExtensions[i].toLowerCase();
if (ext == "jpg" || ext == "png" || ext == "gif") {
// match
}
Another possibility I can think of is a switch
statement, like:
var ext = aExtensions[i].toLowerCase();
switch (ext) {
case "jpg":
case "png":
case "gif":
// match
break;
case default:
// No match
}
I might as well include it (other answers had it first, definitely), but one more I can think of is using a regex, like:
if (/jpg|png|gif/i.test(aExtensions[i])) {
// match
}
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.
What about a regex?
if ( /jpg|png|gif/i.test( aExtensions[i] ) ) {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With