Friday, April 15, 2011

How to extract extension from filename string in Javascript?

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.

From stackoverflow
  • 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

    santanu : I got the thing I want thanx....
    meandmycode : 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
    cherouvim : yes, my solution is very simplistic, but I've documented it's drawbacks ;)
  • 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);
    
    Crescent Fresh : Doesn't work with "file" variants (ie no extension).
  • I use code below:

    var fileSplit = filename.split('.');
    var fileExt = '';
    if (fileSplit.length > 1) {
    fileExt = fileSplit[fileSplit.length - 1];
    } 
    return fileExt;
    
  • 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>
    
  • I would recommend using lastIndexOf() as opposed to indexOf()

    var myString = "this.is.my.file.txt"
    alert(x.substring(x.lastIndexOf(".")+1))
    
  • 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
    

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.