PUBLISHED ON: MARCH 1, 2023
JavaScript Program to Get File Extension
JavaScript is a potent programming language that has gained immense popularity over the years, primarily as a result of its capacity to generate dynamic web pages. JavaScript's ability to manipulate files on the client-side is one of its essential capabilities. This article will discuss a JavaScript program that uses a file extension.
We also have an interactive JavaScript course where you can learn JavaScript from basics to advanced and get certified. Check out the course and learn more from here.
Program to Get File Extension Using split() and pop()
In the code given below, the extension of the filename is extracted using the split()
method and the pop()
method.
- The filename is split into individual array elements using the
split()
method.
Here, filename.split('.')
gives ["module", "js"] by splitting the string. And also ["module", "txt"].
Now, the pop()
method is used to return the last array element used in the extension.
// JavaScript Program to get the file extension
function getFileExtension(filename){
// extension of file
const extension = filename.split('.').pop();
return extension;
}
// passing the filename
const res1 = getFileExtension('module.js');
console.log(res1);
const res2 = getFileExtension('module.txt');
console.log(res2);
js
txt
Program to Get File Extension Using substring() and lastIndexOf()
In the code given below, the extension of the filename is extracted using the substring()
method and the lastIndexOf()
method.
filename.lastIndexOf('.') + 1
returns the last position of .
in the filename. 1 is added because the position count starts from 0.
- The
filename.length
property returns the length
of the string.
substring(filename.lastIndexOf('.') + 1, filename.length)
method returns characters between the given indexes. For example, 'module.js'.substring(8, 10)
returns js.
- The OR
||
operator is used to return the original string if there is no .
in the filename.
// JavaScript Program to get the file extension
function getFileExtension(filename){
// get file extension
const extension = filename.substring(filename.lastIndexOf('.') + 1, filename.length);
return extension;
}
const res1 = getFileExtension('module.js');
console.log(res1);
const res2 = getFileExtension('test.txt');
console.log(res2);
js
txt
Conclusion
This article concludes with a discussion of a JavaScript programme that uses a hook to extract the file extension from a filename. Using the aforementioned techniques, you can generate code that is easily maintained and reduces the likelihood of errors.