267

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.

0

10 Answers 10

470

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
Sign up to request clarification or add additional context in comments.

19 Comments

@Tomalak... this is cool! would you mind explaining what each part of the reg ex is doing?
@Hristo Certainly not. See above.
I'd suggest using var re = /(?:\.([^./]+))?$/; to capture following case as well: a.b/c -> c is the file and has no suffix
@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.
@AndrWeisR It's the maintainer's fault when they are regex illiterate. It's a thing one can learn.
|
400

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

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.
Regex seems like overkill for this. This is simpler to think/reason about. I use this solution for most cases.
On the contrary 'split' is actually overkill. So many string/array allocations.
This '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 ?
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.
|
242

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

Doesn't work with "file" variants (ie no extension).
Actually, 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.
const extension = path.extname(url);
substr it is considered a legacy function and should be avoided when possible.
37

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

var myString = "this.is.my.file.txt"
alert(myString.substring(myString.lastIndexOf(".")+1))

Comments

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!

1 Comment

Repeated answer
3

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

@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...
I didn't downvote.
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

3 Comments

I got the thing I want thanx....
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
yes, my solution is very simplistic, but I've documented it's drawbacks ;)
1

I use code below:

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

2 Comments

this one is better then lastIndexof method
@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.
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>

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.