How to Get File Extension in Javascript
In this tutorial, we will go through how to get the extension of a user-selected file in JavaScript.
Step 1
The first step is to check whether the user's browser supports JavaScript FileRead and Blob. If it doesn't (the vast majority will), we can't probe the file easily.
<input type="file" name="upload" id="upload">
var elm = document.getElementById('upload');
elm.addEventListener('change', function() {
if (window.FileReader && window.Blob) {
} else {
alert('Please update your browser to support this feature.');
}
});
Step 2
Now, access the file(s) with the .files
property, loop through them and access the name of the file with the .name
property.
var elm = document.getElementById('upload');
elm.addEventListener('change', function() {
if (window.FileReader && window.Blob) {
var files = elm.files;
for (let i of files) {
console.log(i.name);
}
} else {
alert('Please update your browser to support this feature.');
}
});
example.jpg
Step 3
Now we have the file name we can get the extension using some RegEx before transforming the result to lowercase to maintain consistency.
// get file extension
var re = /(?:\.([^.]+))?$/;
var ext = re.exec(i.name)[1].toLowerCase();
console.log(ext);
jpg
Conclusion
Here is the full example of how to get the extension for one or many files in JavaScript:
<input type="file" name="upload" id="upload">
var elm = document.getElementById('upload');
elm.addEventListener('change', function() {
if (window.FileReader && window.Blob) {
var files = elm.files;
for (let i of files) {
// get file extension
var re = /(?:\.([^.]+))?$/;
var ext = re.exec(i.name)[1].toLowerCase();
console.log(ext);
}
} else {
alert('Please update your browser to support this feature.');
}
});