242

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.

0m3r
  • 12,286
  • 15
  • 35
  • 71
santanu
  • 5,217
  • 7
  • 26
  • 17

10 Answers10

443

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
Tomalak
  • 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
  • 4
    I'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
  • 1
    I 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
  • 1
    Too 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
348

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'
Mo.
  • 26,306
  • 36
  • 159
  • 225
Robert Mullaney
  • 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
  • 7
    Regex 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
  • 6
    On 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
  • 7
    Returning 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
234

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
  • 687,336
  • 108
  • 737
  • 1,005
35

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

var myString = "this.is.my.file.txt"
alert(myString.substring(myString.lastIndexOf(".")+1))
fregante
  • 29,050
  • 14
  • 119
  • 159
Russ Cam
  • 124,184
  • 33
  • 204
  • 266
22

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!

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
Afzal Ali
  • 269
  • 2
  • 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

The iOSDev
  • 5,237
  • 7
  • 41
  • 78
Vladimir Djuricic
  • 4,323
  • 1
  • 21
  • 22
2
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
  • 31,725
  • 15
  • 104
  • 153
  • I got the thing I want thanx.... – santanu Mar 25 '09 at 10:07
  • 1
    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 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
1

I use code below:

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

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
  • 5,296
  • 4
  • 39
  • 50
0

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.

Leo
  • 37,640
  • 8
  • 75
  • 100
Ravinder Singh
  • 3,113
  • 6
  • 30
  • 46