Here in this article, we going to learn how to get file extension in javascript ( client side), so we can validate it. We are using 2 different approaches to achieve it.
Two ways to get the file extension.
- Use Regex to get file type.
- Using split and pop method to get file type.
HTML Markup:
Here we added a form tag, with a file upload control and button tag. On button click, we call getFileExtention method, which gives an alert message and display the extension of the uploaded file. The code looks like as written below.
<form action="/uploadFile">
<input id="myFile" type="file" name="file">
<button onclick="fnGetExtension()">Get Extension</button>
</form>
Method 1: Using regex to get file extension
Here we have regex value which gives us the file extension. This Regex is useful for extracting file extensions from URLs, even if URL contains ?foo=123 query strings or #hash values.
Javascript Code:
function fnGetExtension() {
//Get the file input element by its id
var fileInput = document.getElementById('myFile');
//Get the file name
var fileName = fileInput.files[0].name;
// Regular expression for file extension.
var patternFileExtension = /\.([0-9a-z]+)(?:[\?#]|$)/i;
//Get the file Extension
var fileExtension = (fileName).match(patternFileExtension);
alert(fileExtension);
}
Method 2: Using split and pop method to get file type.
Here we use split() method and use a dot (.) as a separator, and with pop() method we get the extension.
Javascript Code:
function fnGetExtension() {
//Get the file input element by its id
var fileInput = document.getElementById('myFile');
//Get the file name
var fileName = fileInput.files[0].name;
//Get the file Extension
var fileExtension = fileName.split('.').pop();
alert(fileExtension);
}
Conclusion: Here we have shown how to get file extension with and without using regular expression in javascript. This further can we used to file validation while uploading files.