returning true if a condition is met

Viewed 80

I have to color a div based on the file extension. However, sometimes the file extension may not match with any of the file extensions that i have mentioned below so in that case I will color the div white. But with my condition below, it's always white even if the file extension matches with 'docx', 'doc', 'txt' what am I doing wrong here?

if(!this.fileExtension.toLowerCase().match('docx', 'doc', 'txt')) return ''

2 Answers

In the example, you are only matching with the 'docx' extension, maybe encapsulating your code in a for loop that checks for all needed examples can be a solution:

let found = False;
for (ext in ["docx", "doc", "txt"]) {
     if (this.fileExtension.toLowerCase().match(ext)) {
         found = True;
         break;
     }
}
// work your magic with the found variable...

I take a look at the match javascript documentation : https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/String/match

I think this code is acceptable for what your are trying to do :

const extension = "html"

if(!extension.match(/^(doc|docx|txt)$/i)) {
    console.log("white");
}

// print white

The 'i' parameter is for regex case insensitive

You can do that too

return extension.match(/^(doc|docx|txt)$/i) ? "chose a color here" : "white";
Related