Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a extension of a file using jquery or javascript? [duplicate]

Tags:

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!!!

like image 747
IamIronMAN Avatar asked Nov 12 '10 13:11

IamIronMAN


People also ask

How to get file extensions using JavaScript?

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.

How to combine two JavaScript methods to get the file extension?

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.

How to create an extension for a HTML file?

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

How to get the file extension of the selected file?

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.


1 Answers

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.

like image 172
Nick Craver Avatar answered Oct 23 '22 16:10

Nick Craver