Table of Contents
Just like any other programming language, you can use JavaScript to work with files.
When you are working with files, one of the most useful things to know is the file's extension.
In this post, we'll learn how to extract the file's extension from the file name in JavaScript.
Extracting the file extension from the file name
To extract the file extension from the file name, we'll use the split()
method.
The split()
method splits a string into an array of substrings using the parameter as the delimiter, and then returns the substrings as an array.
JAVASCRIPTconst fileName = "my-file.txt";
const fileExtension = fileName.split(".");
console.log(fileExtension);
BASH(2) ['my-file', 'txt']
From there, we can use the pop()
method to get the last element in the array.
Let's see the full example:
JAVASCRIPTconst fileName = "my-file.txt";
const fileExtension = fileName.split(".").pop();
console.log(fileExtension);
BASHtxt
This works because in almost all cases, the file extension is the last part of the file name, after the last dot.
For reusability, we can also turn this into a function:
JAVASCRIPTconst getFileExtension = (fileName) => {
return fileName.split(".").pop();
}
const fileExtension = getFileExtension("my-file.txt");
console.log(fileExtension);
BASHtxt
Conclusion
In this post, we looked at how to extract the file extension from the file name in JavaScript.
Simply use the split()
method to split the file name into an array of substrings by splitting on a .
, and then use the pop()
method to get the last element in the array, which is usually the accurate file extension.
Thanks for reading!
- Getting Started with TypeScript
- Getting Started with Express
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- Using Puppeteer and Jest for End-to-End Testing
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Learn how to build a Slack Bot using Node.js
- Creating a Twitter bot with Node.js
- Setting Up a Local Web Server using Node.js
- How To Create a Modal Popup Box with CSS and JavaScript
- Getting Started with Moon.js