Method 1: Using split() and pop() Methods
We can use the combination of pop() and split() methods to get the file extension. The split() method returns a new array after splitting a text/string into an array of substrings and it will be separated by the character we passed to it in the method parameter.
Let’s look at an example of a split method where we will initiate a variable with a file name and then split that on the “.” character:
var returned = filename.split(".");
alert(returned); //code, js
We can see in the above screenshot that the code and js are returned as separate separated by a comma.
var returned = filename.pop();
alert(returned); // js
We can see in the below screenshot that the pop() method popped the last element of the filename array and returned it:
Let us now combine the two i-e pop() method and split() method to achieve our task of getting the extension of a file:
//extract file extension
const extension = fileName.split('.').pop();
// passing the filename
const fileExtension = getFileExtension('code.js');
In the above code, we made a small function with the name of getFileExtension() so that we don’t have to repeat the process of writing the code again and again. The getFileExtension() function receives a filename parameter and then splits and pops the last element of the filename and returns the result.
Method2: Using substring() and lastIndexOf() Methods
var extract = machine.substring(2, 5);
alert(extract); // rop
The lastIndexOf() method is used to find the location of a specified character or a substring in a string and returns an index value of the last occurrence of a specified value in a string. The lastIndexOf() returns a value of negative one (-1) if the value is not found.
var lastIndex = machine.lastIndexOf("a");
alert(lastIndex); // 6
Let us now combine the two methods, substring() and lastIndexOf() to extract the file extension from a filename:
return fileName.substring(fileName.lastIndexOf(".") + 1);
var filename = "code.js";
var extension = getFileExtension(filename);
alert(extension); // js
The fileName.lastIndexOf(“.”)+1 returns the last position or index of the . In the file name and the +1 is because the index starts from 0.