While working with files, sometimes we need to validate file extensions or get file extension for independent use like displaying file based on extensions. With HTML input, we can ask a user to upload a file to webpage.
Validating user input is necessary while file upload. It can be risky to enable user to upload all types of files to a server. For that, we can add client-side or server-side validation. But before implementing, we need to get and specify file extensions to enable upload.
In this tutorial, we will take file type input from user and display its extension using regex and split & pop method. Here, we will take examples of both methods.
Before starting let's add form and input with file type into our webpage. You can use existing forms or elements as per your requirement.
Here, we have created a form and added input with file type. We have also added an empty paragraph tag with a unique id. In a further example, we will use this p tag to display the extension of a file.
Get File Extension Using Regex
The regex finds patterns in string and returns a response based on pattern. In files, name and extensions are divided by . and extensions can not contain any special characters. So we will define our regex based on this logic.
Get File Extension Using Split and Pop Method
In this method, we will use split() to split string into array with a dot. Then we will use pop() function to get last element from array which is an extension of a file.
Let's take an example to understand it.
Here, we'll get file name just like previous method. Then split name extension into array and display user extension which last element of array.
Conclusion
In this article, we have taken a simple example to get file extensions. This example will get you file extension. From now on you can use extensions for your requirement like validation or showing user messages or more.