Function that ignores case

I wrote this function to check the file extension of a potential path string.

function checkTyp(str) {
    typs = ["mp4", "avi", "wmv", "mov", "mp2", "flv"]
    for (i=0; i<typs.length; i++) {
        if (str.slice(str.lastIndexOf(".")+1) == typs[i]) {
            return 1
        } 
    }
    return 0
}

I have now realized that it only results in a return type of true if the extension is lowercase. So if the string is something like this,
D:\Stuff\Video\Daffy One Million Box.mp4
it will work, but if it is like this,
D:\Stuff\Video\Daffy One Million Box.MP4 D:\Stuff\Video\Daffy One Million Box.Mp4
it will not. How could I make it so any combination of uppercase and lowercase will be read the same? I know I could just put the uppercase version in the Array. However, I feel knowing an efficient way to do it would be a JavaScript skill worth learning. Thanks

Just downcase the string you are passing to the checkTyp function.

Here’s an example:

function checkType(str) {
  var extensions = ["mp4", "avi", "wmv", "mov", "mp2", "flv"],
      extn = str.toLowerCase().split('.').pop();
  
  return extensions.indexOf(extn) >= 0;
}

Test:

checkType("D:\Stuff\Video\Daffy One Million Box.mp4");
=> true

checkType("D:\Stuff\Video\Daffy One Million Box.MP4");
=> true

checkType("D:\Stuff\Video\Daffy One Million Box.Mp4");
=> true

checkType("D:\Stuff\Video\Daffy One Million Box.docx");
=> false
2 Likes

Really cool way of doing it. This helps me learn and understand. Thanks

1 Like

How did you get your code to indent and be different colors? Thanks

Using three backticks (also called code fences)

```
code goes here
```
2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.