tags:

views:

1045

answers:

6

how would i get the File extension of the file in a variable? like if I have a file as 1.txt I need the txt part of it.

+2  A: 
var x = "1.txt";
alert (x.substring(x.indexOf(".")+1));

note 1: this will not work if the filename is of the form file.example.txt
note 2: this will fail if the filename is of the form file

cherouvim
I got the thing I want thanx....
santanu
You could use lastIndexOf, not sure of the browser support (might want to check ie6, but its easy to prototype your own).. you will just want to make sure you ensure you scan from prior to the last character.. so that 'something.' isn't matched, but 'something.x' would
meandmycode
yes, my solution is very simplistic, but I've documented it's drawbacks ;)
cherouvim
+8  A: 

Use the lastIndexOf method to find the last period in the string, and get the part of the string after that:

var ext = fileName.substr(fileName.lastIndexOf('.') + 1);
Guffa
Doesn't work with "file" variants (ie no extension).
Crescent Fresh
A: 

I use code below:

var fileSplit = filename.split('.');
var fileExt = '';
if (fileSplit.length > 1) {
fileExt = fileSplit[fileSplit.length - 1];
} 
return fileExt;
Pragmainline
+1  A: 

This is the solution if your file has more . (dots) in the name.

<script type="text/javascript">var x = "file1.asdf.txt";
var y = x.split(".");
alert(y[(y.length)-1]);</script>
Bogdan Constantinescu
+1  A: 

I would recommend using lastIndexOf() as opposed to indexOf()

var myString = "this.is.my.file.txt"
alert(x.substring(x.lastIndexOf(".")+1))
Russ Cam
+4  A: 

A variant that works with all of the following inputs:

  • "file.name.with.dots.txt"
  • "file.txt"
  • "file"
  • ""
  • null

would be:

var re = /(?:\.([^.]+))?$/;

var ext = re.exec("file.name.with.dots.txt")[1];   // "txt"
var ext = re.exec("file.txt")[1];                  // "txt"
var ext = re.exec("file")[1];                      // undefined
var ext = re.exec("")[1];                          // undefined
var ext = re.exec(null)[1];                        // undefined
Tomalak