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
2009-03-25 10:02:15
I got the thing I want thanx....
santanu
2009-03-25 10:07:38
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
2009-03-25 10:09:41
yes, my solution is very simplistic, but I've documented it's drawbacks ;)
cherouvim
2009-03-25 10:33:30
+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
2009-03-25 10:06:38
A:
I use code below:
var fileSplit = filename.split('.');
var fileExt = '';
if (fileSplit.length > 1) {
fileExt = fileSplit[fileSplit.length - 1];
}
return fileExt;
Pragmainline
2009-03-25 10:06:45
+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
2009-03-25 10:06:51
+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
2009-03-25 10:09:38
+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
2009-03-25 10:18:21