i want to check the type of uploaded file. If name like example.txt
, i want to get the .txt
part only. How can i achieve it using Jquery or javascript.
Any Suggestions or links would be appreciative!!!
To get file extensions using JavaScript, there are so many ways. The most useful ones are: Above methods are described below one by one with the proper example. The full filename is first obtained by selecting the file input and getting its value property.
Combining the 2 JavaScript methods will also return the file extension. The substr () method will extract or fetch certain values from a string. The general syntax is: string. substr ( start, length ). The first parameter start, will be a numeric value and second parameter “length†too accepts a numeric value.
Step 1. Make a HTML file and define markup, scripting and styling We make a HTML file and save it with a name get_file_extension.html
The first part will be the filename and the second part will be the extension of the file. The extension can then be got by popping from the array the last string with the pop () method. This is hence the file extension of the file selected.
A simple solution is .split()
and .pop()
to get the last string in the array, like this:
var ext = fileName.split('.').pop();
This will get you just "txt"
without the .
, just append if needed. This also works on say: My.File.name.has.an extension.txt
as well. If it doesn't have an extension it'll return the file name, so you may want to check for this...or go a completely different direction and validate against a set or known extensions via regex.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With