Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript formatting for if condition [duplicate]

Possible Duplicate:
Check variable equality against a list of values
Javascript: Comparing SINGLE Value Against MULTIPLE Values with OR Operands

First of all I am new to javascript side. Please let me know is there any simple way of formating the below code.

if( fileName== 'doc' || fileName=='docx' || fileName=='xls' || fileName=='xlsx' || fileName=='ppt' || fileName=='pdf' ){

Do something

} else{

    Do something

}
like image 325
user1817630 Avatar asked Jan 08 '13 15:01

user1817630


3 Answers

var SUPPORTED_FILE_EXTENSIONS = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pdf'];

if(SUPPORTED_FILE_EXTENSIONS.indexOf(fileName) != -1){
    //Do Something
} else {
    //Do Something Else
}

Array.indexOf() - Note that this also includes information about adding backward compatibility support for older browsers (I.E. IE).

like image 100
Briguy37 Avatar answered Oct 03 '22 05:10

Briguy37


var validTypes = /docx?|xlsx?|ppt|pdf/;

if (fileName.match(validTypes)) {
    ...
}

Note: the question mark, ?, in the Regular Expression indicates the previous character is optional so it can match both doc and docx the pipe, |, indicates or so it will match doc or xls, etc.

like image 26
JaredMcAteer Avatar answered Oct 03 '22 07:10

JaredMcAteer


maybe something like

var filenames = ['doc','docx','xls','xlsx','ppt','pdf'];
if(filenames.indexOf(fileName) >= 0 ) {
  // Do something
} else {
    // Do something else
}
like image 41
user160820 Avatar answered Oct 03 '22 07:10

user160820