How can I get file extensions with JavaScript?

后端 未结 30 1809
终归单人心
终归单人心 2020-11-22 09:37

See code:

var file1 = \"50.xsl\";
var file2 = \"30.doc\";
getFileExtension(file1); //returns xsl
getFileExtension(file2); //returns doc

function getFileExt         


        
相关标签:
30条回答
  • 2020-11-22 10:20

    There's also a simple approach using ES6 destructuring:

    const path = 'hello.world.txt'
    const [extension, ...nameParts] = path.split('.').reverse();
    console.log('extension:', extension);

    0 讨论(0)
  • 2020-11-22 10:21

    // 获取文件后缀名
    function getFileExtension(file) {
      var regexp = /\.([0-9a-z]+)(?:[\?#]|$)/i;
      var extension = file.match(regexp);
      return extension && extension[1];
    }
    
    console.log(getFileExtension("https://www.example.com:8080/path/name/foo"));
    console.log(getFileExtension("https://www.example.com:8080/path/name/foo.BAR"));
    console.log(getFileExtension("https://www.example.com:8080/path/name/.quz/foo.bar?key=value#fragment"));
    console.log(getFileExtension("https://www.example.com:8080/path/name/.quz.bar?key=value#fragment"));

    0 讨论(0)
  • 2020-11-22 10:22

    A one line solution that will also account for query params and any characters in url.

    string.match(/(.*)\??/i).shift().replace(/\?.*/, '').split('.').pop()
    
    // Example
    // some.url.com/with.in/&ot.s/files/file.jpg?spec=1&.ext=jpg
    // jpg
    
    0 讨论(0)
  • 2020-11-22 10:23

    Try this:

    function getFileExtension(filename) {
      var fileinput = document.getElementById(filename);
      if (!fileinput)
        return "";
      var filename = fileinput.value;
      if (filename.length == 0)
        return "";
      var dot = filename.lastIndexOf(".");
      if (dot == -1)
        return "";
      var extension = filename.substr(dot, filename.length);
      return extension;
    }
    
    0 讨论(0)
  • 2020-11-22 10:24

    I'm sure someone can, and will, minify and/or optimize my code in the future. But, as of right now, I am 200% confident that my code works in every unique situation (e.g. with just the file name only, with relative, root-relative, and absolute URL's, with fragment # tags, with query ? strings, and whatever else you may decide to throw at it), flawlessly, and with pin-point precision.

    For proof, visit: https://projects.jamesandersonjr.com/web/js_projects/get_file_extension_test.php

    Here's the JSFiddle: https://jsfiddle.net/JamesAndersonJr/ffcdd5z3/

    Not to be overconfident, or blowing my own trumpet, but I haven't seen any block of code for this task (finding the 'correct' file extension, amidst a battery of different function input arguments) that works as well as this does.

    Note: By design, if a file extension doesn't exist for the given input string, it simply returns a blank string "", not an error, nor an error message.

    It takes two arguments:

    • String: fileNameOrURL (self-explanatory)

    • Boolean: showUnixDotFiles (Whether or Not to show files that begin with a dot ".")

    Note (2): If you like my code, be sure to add it to your js library's, and/or repo's, because I worked hard on perfecting it, and it would be a shame to go to waste. So, without further ado, here it is:

    function getFileExtension(fileNameOrURL, showUnixDotFiles)
        {
            /* First, let's declare some preliminary variables we'll need later on. */
            var fileName;
            var fileExt;
            
            /* Now we'll create a hidden anchor ('a') element (Note: No need to append this element to the document). */
            var hiddenLink = document.createElement('a');
            
            /* Just for fun, we'll add a CSS attribute of [ style.display = "none" ]. Remember: You can never be too sure! */
            hiddenLink.style.display = "none";
            
            /* Set the 'href' attribute of the hidden link we just created, to the 'fileNameOrURL' argument received by this function. */
            hiddenLink.setAttribute('href', fileNameOrURL);
            
            /* Now, let's take advantage of the browser's built-in parser, to remove elements from the original 'fileNameOrURL' argument received by this function, without actually modifying our newly created hidden 'anchor' element.*/ 
            fileNameOrURL = fileNameOrURL.replace(hiddenLink.protocol, ""); /* First, let's strip out the protocol, if there is one. */
            fileNameOrURL = fileNameOrURL.replace(hiddenLink.hostname, ""); /* Now, we'll strip out the host-name (i.e. domain-name) if there is one. */
            fileNameOrURL = fileNameOrURL.replace(":" + hiddenLink.port, ""); /* Now finally, we'll strip out the port number, if there is one (Kinda overkill though ;-)). */  
            
            /* Now, we're ready to finish processing the 'fileNameOrURL' variable by removing unnecessary parts, to isolate the file name. */
            
            /* Operations for working with [relative, root-relative, and absolute] URL's ONLY [BEGIN] */ 
            
            /* Break the possible URL at the [ '?' ] and take first part, to shave of the entire query string ( everything after the '?'), if it exist. */
            fileNameOrURL = fileNameOrURL.split('?')[0];
    
            /* Sometimes URL's don't have query's, but DO have a fragment [ # ](i.e 'reference anchor'), so we should also do the same for the fragment tag [ # ]. */
            fileNameOrURL = fileNameOrURL.split('#')[0];
    
            /* Now that we have just the URL 'ALONE', Let's remove everything to the last slash in URL, to isolate the file name. */
            fileNameOrURL = fileNameOrURL.substr(1 + fileNameOrURL.lastIndexOf("/"));
    
            /* Operations for working with [relative, root-relative, and absolute] URL's ONLY [END] */ 
    
            /* Now, 'fileNameOrURL' should just be 'fileName' */
            fileName = fileNameOrURL;
            
            /* Now, we check if we should show UNIX dot-files, or not. This should be either 'true' or 'false'. */  
            if ( showUnixDotFiles == false )
                {
                    /* If not ('false'), we should check if the filename starts with a period (indicating it's a UNIX dot-file). */
                    if ( fileName.startsWith(".") )
                        {
                            /* If so, we return a blank string to the function caller. Our job here, is done! */
                            return "";
                        };
                };
            
            /* Now, let's get everything after the period in the filename (i.e. the correct 'file extension'). */
            fileExt = fileName.substr(1 + fileName.lastIndexOf("."));
    
            /* Now that we've discovered the correct file extension, let's return it to the function caller. */
            return fileExt;
        };
    

    Enjoy! You're Quite Welcome!:

    0 讨论(0)
  • 2020-11-22 10:25

    I just realized that it's not enough to put a comment on p4bl0's answer, though Tom's answer clearly solves the problem:

    return filename.replace(/^.*?\.([a-zA-Z0-9]+)$/, "$1");
    
    0 讨论(0)
提交回复
热议问题