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"
""
null
undefined
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

- 332,285
- 67
- 532
- 628
-
8@Tomalak... this is cool! would you mind explaining what each part of the reg ex is doing? – Hristo Feb 08 '12 at 20:03
-
56@Hristo Certainly not. See above. – Tomalak Feb 08 '12 at 20:57
-
4I'd suggest using var re = /(?:\.([^./]+))?$/; to capture following case as well: a.b/c -> c is the file and has no suffix – Christian Mar 28 '13 at 15:09
-
4@Waxolunist Definitely, if you expect paths. But you'd have to work with system specific separators, the forward slash alone will not do. However, the question was about filenames. – Tomalak Mar 28 '13 at 15:24
-
@Tomalak I think that HTTP only works with forward slashes as the separators, correct? – MiJyn Jul 25 '13 at 18:21
-
1@MiJyn Yes. But HTTP has nothing to do with the question. – Tomalak Jul 25 '13 at 23:13
-
try using `filepath.match((/\.[\w]+$/g)` for example `'/path/to/file/file.with.many.dots'.match((/\.[\w]+$/g)` – yegodz Feb 19 '15 at 20:49
-
or as a function `function ext(str) { var ex; return ((ex = str.match(/\.[\w]+$/g)) && (ex = ex[0])) }` – yegodz Feb 19 '15 at 20:58
-
1@user This is not recommendable because it imposes unnecessary restrictions on the file extension. Not every possible file extension is `\w+`. – Tomalak Feb 20 '15 at 10:24
-
1I think using this regexp for this task is a major overkill. The split-pop solution is way more simple. – Herbertusz Apr 17 '17 at 16:30
-
2@Herbertusz Use what works for you. Split+pop does not return the same results. – Tomalak Apr 17 '17 at 16:32
-
1Too complicated. Someone else is probably going to have to maintain this a year after the original coder writes it, and they'll have no idea what it's doing. The 'lastIndexOf' solution is much easier to understand. – AndrWeisR Jun 25 '19 at 07:25
-
1@AndrWeisR It's the maintainer's fault when they are regex illiterate. It's a thing one can learn. – Tomalak Jun 25 '19 at 09:18
-
3@Tomalak That is completely the wrong attitude to writing maintainable software. – AndrWeisR Jun 26 '19 at 01:47
-
This solution has issues with hidden files, eg.: `.ignore`, which should result in null extension. Modifying the regex for this becomes: `/(?:[^\.]\.([^.]+))?$/`. To generalize this solution to work for paths: `(?:[^\/]\.([^\.\/]+))?$` – KDumont Mar 07 '23 at 23:33
-
1@Tomalak upvote for elegant and memorable 'Explanation' section that clearly shows what each part of your regex does – antonymott Jul 21 '23 at 17:51
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'

- 26,306
- 36
- 159
- 225

- 3,481
- 1
- 14
- 2
-
Thank you! This one is the most clear to me. I'm passing the filename to a function, so I had to do a null check before calling split. – Lifes Jan 12 '13 at 00:59
-
7Regex seems like overkill for this. This is simpler to think/reason about. I use this solution for most cases. – aashtonk May 02 '17 at 19:01
-
6On the contrary 'split' is actually overkill. So many string/array allocations. – Sayam Qazi Jun 14 '18 at 05:51
-
This 'http://example.com/questions/680929' => 'com/questions/680929' doesn't have any extension. How to get empty string or null or undefined for this case as there is no extension ? – Owais Jun 09 '20 at 12:09
-
7Returning the full string when there is no file extension seems like the wrong move here. If a file or path does not have an extension I'd rather return a `false` or a `null` instead of the String I just passed in. That would at least allow you to handle for those cases. – Joshua Pinter Jul 23 '20 at 15:01
-
One of the most beautiful and long standing answer on stackoverflow I have ever seen. – Alan Spurlock Feb 28 '23 at 14:14
-
@Owais you could check the length of the array split returned: `const splitted = filename.split('.');` and then `if (splitted.length > 1) ...`. Beware of possible `undefined` returned value. – aProgger Jun 20 '23 at 07:56
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);

- 687,336
- 108
- 737
- 1,005
-
1
-
29Actually, it does. It returns the entire file name, which is as good as anything in that case IMO. If you want an empty string instead, you'll need to use an (gasp!) if statement. Also, if using node.js with JavaScript, see the "path" built-in module. – Jon Watte Jul 19 '11 at 03:14
-
7
-
1`substr` it is considered a legacy function and should be avoided when possible. – Przemek Nowicki Nov 07 '22 at 17:13
I would recommend using lastIndexOf() as opposed to indexOf()
var myString = "this.is.my.file.txt"
alert(myString.substring(myString.lastIndexOf(".")+1))
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!

- 39,603
- 20
- 94
- 123

- 269
- 2
- 2
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

- 5,237
- 7
- 41
- 78

- 4,323
- 1
- 21
- 22
-
@itsbruce using terms "better" and down-voting kinda sucks... This works. P.S. If question was "What is the best way to get the extension from file name" - I would agree completely... – Vladimir Djuricic Dec 21 '17 at 11:43
-
1
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

- 31,725
- 15
- 104
- 153
-
-
1You 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 Mar 25 '09 at 10:09
-
yes, my solution is very simplistic, but I've documented it's drawbacks ;) – cherouvim Mar 25 '09 at 10:33
I use code below:
var fileSplit = filename.split('.');
var fileExt = '';
if (fileSplit.length > 1) {
fileExt = fileSplit[fileSplit.length - 1];
}
return fileExt;
-
-
@CrackerKSR why would you say it's "better"? Looks very archaic to be honest, using `var`, and not using `Array.pop()` or `Array.at(-1)` e.g. – Victor Zamanian Jan 09 '23 at 14:39
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>

- 5,296
- 4
- 39
- 50
get the value in the variable & then separate its extension just like this.
var find_file_ext=document.getElementById('filename').value;
var file_ext=/[^.]+$/.exec(find_file_ext);
This will help you.

- 37,640
- 8
- 75
- 100

- 3,113
- 6
- 30
- 46