Skip to main content

How to check file is an image in javascript using filename

You can check if the file is an image using the filename in javascript. This function helps you get the file extension and return true or false if the file extension does not exist in the provided file extensions array.

  • Check the file extension in javascript using filename and return true if the file is an image

    <script>
        function getFileExtension(fileName){
            var  fileExtension;
            fileExtension = fileName.replace(/^.*\./, '');
            return fileExtension;
        }
        function isIMage(fileName){
            var fileExt = getFileExtension(fileName);
            var imagesExtension = ["png", "jpg", "jpeg"];
            if(imagesExtension.indexOf(fileExt) !== -1){
                return true;
            } else{
                return false;
            }
        }
        console.log(isIMage('filename.jpg'));
    </script>

    You have to pass the filename to function. This function first checks the file extension and after that it returns true and false on the basis of the provided file extension array.

  • Back to code snippet queries related javascript