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.
10 Answers
A variant that works with all of the following inputs:
"file.name.with.dots.txt""file.txt""file"""nullundefined
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
var ext = re.exec(undefined)[1]; // undefined
Explanation
(?: # begin non-capturing group
\. # a dot
( # begin capturing group (captures the actual extension)
[^.]+ # anything except a dot, multiple times
) # end capturing group
)? # end non-capturing group, make it optional
$ # anchor to the end of the string
19 Comments
I personally prefer to split the string by . and just return the last array element :)
var fileExt = filename.split('.').pop();
If there is no . in filename you get the entire string back.
Examples:
'some_value' => 'some_value'
'.htaccess' => 'htaccess'
'../images/something.cool.jpg' => 'jpg'
'http://www.w3schools.com/jsref/jsref_pop.asp' => 'asp'
'http://stackoverflow.com/questions/680929' => 'com/questions/680929'
7 Comments
false or a null instead of the String I just passed in. That would at least allow you to handle for those cases.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);
4 Comments
const extension = path.extname(url);substr it is considered a legacy function and should be avoided when possible.I would recommend using lastIndexOf() as opposed to indexOf()
var myString = "this.is.my.file.txt"
alert(myString.substring(myString.lastIndexOf(".")+1))
Comments
Better to use the following; Works always!
var ext = fileName.split('.').pop();
This will return the extension without a dot prefix. You can add "." + ext to check against the extensions you wish to support!
1 Comment
Try this. May solve your problem.
var file_name_string = "file.name.string.png"
var file_name_array = file_name_string.split(".");
var file_extension = file_name_array[file_name_array.length - 1];
Regards
2 Comments
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
3 Comments
I use code below:
var fileSplit = filename.split('.');
var fileExt = '';
if (fileSplit.length > 1) {
fileExt = fileSplit[fileSplit.length - 1];
}
return fileExt;
2 Comments
var, and not using Array.pop() or Array.at(-1) e.g.