How to find File extension using JavaScript

How to get an extension of the filename and How to validate any document using Javascript.  In this Javascript tutorial, let’s write JS code to read a file, read the extension of the file and validate the file type.

  • How to get the extension of the filename Javascript.
  • Validate document-type files in Javascript.
  • Validate Media-type file in Javascript.
  • Validate Image-type files in Javascript.

How to get an extension of the filename in Javascript?

Problem statement

Create an HTML file as xyz.html with JS function that will return the extension of a filename and print the generated extension on the browser console.

Solution

  • First create Html file as .html
  • Enter heading into <h1> </h1> tag
  • Create input type button with onclick  attribute that is “checkFileExtension”
  • Create JS function inside this  use filename=document.( querySelector(‘#file1’).value)
  • When we use the split method it splits a string into an array if (“.”) is used as a separator  String will separate between characters and after the dot it will pop the extension on the output screen.
  • Run the html file.

JS code  to get the extension of the filename

<!DOCTYPE html>
<html>

<head>
    <title>file extensions using JavaScript</title>
</head>

<body style="text-align: center;">
    <h1 style="color: blue;">file extension</h1>
    <h4>here check extension</h4>
    <form>
        <input type="file" id="file1" />
        <input type="button" value="Check Extension" onclick="checkFileExtension();"/>
    </form>
    <p>The file extension is: <span class="output"></span></p>
    <script>
        function checkFileExtension() 
        {
            fileName = document.querySelector('#file1').value;
            extension = fileName.split('.').pop();
            document.querySelector('.output').textContent = extension;
        };
    </script>
</body>

</html>

Output

In this way, we learned how to get an extension of the filename using the js example.

Validate document-type files in JavaScript

Problem statement

In this, you have to validate document-type files in the javascript function. For that create an HTML file as. html extension and then choose a file from the device and validate it is doctype or not and run the file.

Solution 

  • Create Html file
  • Enter heading into <h3></h3 > tag
  • Enter next heading into a <p></p> tag
  • Use Javascript function in that takes input from a user as choose file from device
  • Initialize filepath as var filePath = fileInput.value; 
  • Next allow only .doc and .docx extensions for validation
  • Use if loop for creating an alert box and display the output on the screen if it is not the output type then it will return false.

JS code to Validate document-type files in JavaScript

<!DOCTYPE html>
<html>
  
<head>
    <title>
        File Type Validation while
        Uploading it using JavaScript
    </title>

</head>
  
<body>
  
    <h3> 
        Validation of file type while 
        uploading using JavaScript? 
    </h3>
  
    <!-- File input field -->
    <p>Upload an Image</p>
    <input type="file" id="file"
        onchange="return fileValidation()" />
  
    <!-- Image preview -->
    <div id="imagePreview"></div>
    <script>
        function fileValidation() {
            var fileInput = 
                document.getElementById('file');
              
            var filePath = fileInput.value;
          
            // Allowing file type
            var allowedExtensions = 
/(\.doc|\.docx|)$/i;
              
            if (!allowedExtensions.exec(filePath)) {
                alert('Invalid file type');
                fileInput.value = '';
                return false;
            } 
        }
    </script>
</body>
  
</html>

Output

How to validate media type files in JavaScript?

Problem statement

In this, you have to validate media file type in javascript for that you have to create an HTML file as xyz.html and  Javascript function which returns media files as an output on the screen.

Solution

  • Create html file as .html
  • Enter heading on <h3></h3> tag
  • Create input type file and id is also file
  • In javascript function initialize file input type as document.getElementById(‘file‘);
  • Allow only /(\.doc|\.docx|\.odt|\.pdf|\.tex|\.txt|\.rtf|\.wps|\.wks|\.wpd)$/i;  this file extensions for validation
  • Use if loop for creating an alert box and display the output on the screen if it is not the output type then it will return false.

JS code to validate media type files in JS

<!DOCTYPE html>
<html>
  
<head>
    <title>
        Validating media files
    </title>
</head>
  
<body>
  
    <h3> 
        Validation of media file type while 
        uploading using JavaScript 
    </h3>
  
    <!-- File input field -->
    <p>Upload an Image</p>
    <input type="file" id="file"
        onchange="return fileValidation()" />
  
    <!-- Image preview -->
    <div id="imagePreview"></div>
    <script>
        function fileValidation() {
            var fileInput = 
                document.getElementById('file');
              
            var filePath = fileInput.value;
          
            // Allowing file type
            var allowedExtensions = 
/(\.doc|\.docx|\.odt|\.pdf|\.tex|\.txt|\.rtf|\.wps|\.wks|\.wpd)$/i;
              
            if (!allowedExtensions.exec(filePath)) {
                alert('Invalid file type');
                fileInput.value = '';
                return false;
            } 
        }
    </script>
</body>
  
</html>

Output

 

How to validate Image type files in JavaScript?

Problem statement

In this, you have to validate image type files in javascript for this create an Html file as.html extension and the Javascript function returns the result as image type file validation.

Solution

  • Create Html file
  • Enter heading on <h3></h3> tag
  • Create input type file and id is also file
  • In javascript function initialize file input type as document.getElementById(‘file‘);
  • Allow only /(\.jpg|\.jpeg|\.png|\.gif)$/i;  this file extension for validation
  • Use if loop for creating an alert box and display the output on the screen if it is not the output type then it will return false.

JS code to validate Image type files in JavaScript

<!DOCTYPE html> <html>
  
<head>
    <title>
        File Type Validation while
        Uploading it using JavaScript
    </title>
</head>
  
<body>
  
    <h3> 
        Validation of file type while 
        uploading using JavaScript? 
    </h3>
  
    
    <!-- File input field -->
    <p>Upload an Image</p>
    <input type="file" id="file"
        onchange="return fileValidation()" />
  
    <!-- Image preview -->
    <div id="imagePreview"></div>
    <script>
        function fileValidation() {
            var fileInput = 
                document.getElementById('file');
              
            var filePath = fileInput.value;
          
            // Allowing file type
            var allowedExtensions = 
                    /(\.jpg|\.jpeg|\.png|\.gif)$/i;
              
            if (!allowedExtensions.exec(filePath)) {
                alert('Invalid file type');
                fileInput.value = '';
                return false;
            } 
            else 
            {
              
                // Image preview
                if (fileInput.files && fileInput.files[0]) {
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        document.getElementById(
                            'imagePreview').innerHTML = 
                            '<img src="' + e.target.result
                            + '"/>';
                    };
                      
                    reader.readAsDataURL(fileInput.files[0]);
                }
            }
        }
    </script>
</body>
</html>

Output

Thus, in this way, we learned How to get an extension of the filename, validate the document type, validate media type and validate image type using Javascript.