Write a JavaScript Program to Get File Extension

In JavaScript, getting the file extension of a file can be accomplished using a few simple steps.

First, we need to extract the filename from the path of the file.

This can be done using the substring method in combination with the lastIndexOf method.

The substring method extracts the characters between two specified indices while the lastIndexOf method finds the last occurrence of a specified value in a string and returns the index of the value.

Once we have the filename, we can use the split method to split the filename into an array of strings at the location of the dot that separates the filename from the extension.

We can then use the pop method to extract the last element of the array, which will be the file extension.

Here is an example JavaScript program that demonstrates this process:

function getFileExtension(filename) {
  var lastIndex = filename.lastIndexOf(".");
  var filenameWithoutExtension = filename.substring(0, lastIndex);
  var extension = filename.split(".").pop();
  return extension;
}

console.log(getFileExtension("example.pdf")); // output: "pdf"
console.log(getFileExtension("example.docx")); // output: "docx"
console.log(getFileExtension("example")); // output: ""

In this program, the getFileExtension function takes in a filename as an argument and returns the file extension.

We first use the lastIndexOf method to find the index of the last occurrence of the dot in the filename.

We then use the substring method to extract the characters from the beginning of the filename up to, but not including, the dot. This gives us the filename without the extension.

Next, we use the split method to split the filename into an array of strings at the location of the dot.

We then use the pop method to extract the last element of the array, which is the file extension.

Finally, we return the file extension.

In the example code, we have used the console log to show the output on the console.

We can modify the function to return the output as a variable and use it in other parts of our code.

In conclusion, getting the file extension in JavaScript is a simple process that involves extracting the filename and using the split method to split the filename into an array of strings at the location of the dot.

We can then use the pop method to extract the last element of the array, which will be the file extension.