Home >>Javascript Programs >How to get the extension of a file using JavaScript

How to get the extension of a file using JavaScript

How to get the extension of a file using JavaScript?

This article explains how to get/find the file extension with JavaScript code. Sometimes programmers facing a problem that what do we do to get the extension of jpeg and png.

JavaScript also provides validation in input forms. Many of the times developers provide a input type file for a user, that user will upload their photo or a profile picture. Sometimes users upload wrong file like psd, pdf, etc. we need that the user only upload png or jpeg extension file. For this we need a validation on input forms and apply some conditions that we only accepts png or jpeg extension file. For this developers need a code for validating the form.

Here, in this post we will help you how to get/find the extension of any file in JavaScript.

Methods

There are so many ways, to get file extensions using JavaScript. The most useful ones are:

  • match() method with regular expression
  • split() and pop() method
  • substring() and lastIndexOf() method

Here we will take an example of Using split() and pop() method

 

Split() method helps you to split the filename into two parts, one is the filename and the second will be the extension of the file.

For getting the extension name we are using the pop() method on the array. It returns and removes the last element of the array.

Let's take an example:

<!DOCTYPE html> 
<html> 
<head> 
	<title>How to get file extensions using JavaScript? </title> 
</head> 
<body> 
	<form> 
		<input type="file" id="file1" /> 
		<input type="button" value="Check Extension" onclick="checkFileExtension();"/> 
	</form> 
	<p>The file extension is: <span class="output1"></span></p> 
	<script language="javascript"> 
		function checkFileExtension() { 
			fileName = document.querySelector('#file1').value; 
			extension = fileName.split('.').pop(); 
			document.querySelector('.output1') .textContent = extension; 
		}; 
	</script> 
</body> 
</html> 
Output:
check file extension javascript

No Sidebar ads