如何使用JavaScript获取文件扩展名?

如何使用JavaScript获取文件扩展名?,javascript,file-extension,Javascript,File Extension,见代码: var file1 = "50.xsl"; var file2 = "30.doc"; getFileExtension(file1); //returns xsl getFileExtension(file2); //returns doc function getFileExtension(filename) { /*TODO*/ } 编辑:奇怪的是(也许不是),replace方法第二个参数中的$1似乎不起作用。。。抱歉。更新的编辑:自从这个问题最初发布以来,很多事情都

见代码:

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

function getFileExtension(filename) {
    /*TODO*/
}

编辑:奇怪的是(也许不是),replace方法第二个参数中的
$1
似乎不起作用。。。抱歉。

更新的编辑:自从这个问题最初发布以来,很多事情都发生了变化-在中以及中都有很多非常好的信息


编辑:因为这是公认的答案;确实好得多:

return filename.split('.').pop();

我以前的回答是:

return /[^.]+$/.exec(filename);
我应该这样做

编辑:对于PhiLho的评论,请使用以下内容:

return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;
测试

"a.b"     (=> "b") 
"a"       (=> "") 
".hidden" (=> "") 
""        (=> "") 
null      (=> "")  


我刚刚意识到,仅仅对p4bl0的答案发表评论是不够的,尽管Tom的答案显然解决了问题:

return filename.replace(/^.*?\.([a-zA-Z0-9]+)$/, "$1");
//用法

扩展名('file.jpeg')

始终返回扩展较低的CA,以便在字段更改时检查它 工作对象:

file.JpEg

文件(无扩展名)

文件。(无扩展)

编辑:

这是另一个我认为更有效的非正则表达式解决方案:

return filename.substring(filename.lastIndexOf('.')+1, filename.length) || filename;
下面可以更好地处理一些特殊情况,尤其是没有扩展名的文件(
.htaccess
等)

它的性能非常好,当点之前没有点或字符串时,它返回
,而不是完整的字符串,从而可以更好地处理转角情况。这是一个精心设计的解决方案,尽管很难阅读。将它粘贴到helpers库中并使用它

旧编辑:

如果您将遇到没有扩展名的文件,或者遇到没有扩展名的隐藏文件(请参阅VisioN对Tom上述答案的评论),那么更安全的实现就是这样的

var a = filename.split(".");
if( a.length === 1 || ( a[0] === "" && a.length === 2 ) ) {
    return "";
}
return a.pop();    // feel free to tack .toLowerCase() here if you want
如果
a.length
为1,则它是一个不带扩展名ie.file的可见文件

如果
a[0]==”
a.length==2
它是一个隐藏文件,没有扩展名ie..htaccess


希望这有助于解决稍微复杂一些的问题。就性能而言,我认为这种解决方案适用于大多数浏览器。但是,对于大多数常见用途,此代码应该是完全可用的。

对于大多数应用程序,一个简单的脚本,如

return /[^.]+$/.exec(filename);
会很好的(由汤姆提供)。然而,这并不是万无一失的。如果提供了以下文件名,则不起作用:

image.jpg?foo=bar
这可能有点过分,但我建议使用url解析器,例如,以避免由于不可预测的文件名而导致的失败

使用该特定函数,可以获得如下文件名:

var trueFileName = parse_url('image.jpg?foo=bar').file;
这将输出不带url变量的“image.jpg”。然后,您就可以随意获取文件扩展名。

尝试以下操作:

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;
}

以下解决方案足够快且短,可用于批量操作并节省额外字节:

 return fname.slice((fname.lastIndexOf(".") - 1 >>> 0) + 2);
下面是另一个单线非regexp通用解决方案:

 return fname.slice((Math.max(0, fname.lastIndexOf(".")) || Infinity) + 1);
对于没有扩展名的名称(例如myfile)或以
dot开头的名称(例如.htaccess),两者都可以正常工作:

如果您关心速度,您可以运行并检查提供的解决方案是否最快,而短的解决方案则非常快:

短篇小说的工作原理:

  • 方法返回子字符串(即
    )在给定字符串(即
    fname
    )中的最后位置。如果未找到子字符串,则方法返回
    -1
  • 文件名中点的“不可接受”位置为
    -1
    0
    ,分别指没有扩展名的名称(例如
    “name”
    )和以点开头的名称(例如
    “.htaccess”
  • >>
    )如果与零一起使用,则会影响将
    -1
    转换为
    4294967295
    -2
    转换为
    4294967294
    的负数,这有助于在边缘情况下保持文件名不变(这是一种技巧)
  • 从按说明计算的位置提取文件名部分。如果位置号大于字符串长度,则方法返回
    “”

  • 如果您想要以相同方式工作的更清晰的解决方案(加上对完整路径的额外支持),请检查以下扩展版本。此解决方案将比以前的一行程序慢,但更容易理解

    function getExtension(path) {
        var basename = path.split(/[\\/]/).pop(),  // extract file name from full path ...
                                                   // (supports `\\` and `/` separators)
            pos = basename.lastIndexOf(".");       // get last position of `.`
    
        if (basename === "" || pos < 1)            // if file name is empty or ...
            return "";                             //  `.` not found (-1) or comes first (0)
    
        return basename.slice(pos + 1);            // extract extension ignoring `.`
    }
    
    console.log( getExtension("/path/to/file.ext") );
    // >> "ext"
    
    函数getExtension(路径){
    var basename=path.split(/[\\/]).pop(),//从完整路径提取文件名。。。
    //(支持“\\”和“/”分隔符)
    pos=basename.lastIndexOf(“.”;//获取“”的最后位置`
    if(basename==“”| | pos<1)//如果文件名为空或。。。
    返回“”;//`.`未找到(-1)或先到(0)
    返回basename.slice(pos+1);//提取扩展名忽略``
    }
    log(getExtension(“/path/to/file.ext”);
    //>>“分机”
    

    这三种变体都可以在客户端的任何web浏览器中使用,也可以在服务器端的NodeJS代码中使用。

    Wallacer的回答很好,但还需要再检查一次

    若文件并没有扩展名,它将使用文件名作为扩展名,这是不好的

    试试这个:

    return ( filename.indexOf('.') > 0 ) ? filename.split('.').pop().toLowerCase() : 'undefined';
    

    不要忘记某些文件可能没有扩展名,因此:

    var parts = filename.split('.');
    return (parts.length > 1) ? parts.pop() : '';
    

    快速,可正确使用路径

    (filename.match(/[^\\\/]\.([^.\\\/]+)$/) || [null]).pop()
    
    一些边缘情况

    /path/.htaccess => null
    /dir.with.dot/file => null
    

    使用split的解决方案速度较慢,使用lastIndexOf的解决方案无法处理边缘情况。

    我只是想与大家分享一下

    fileName.slice(fileName.lastIndexOf('.'))
    
    尽管这有一个缺点,即没有扩展名的文件将返回最后一个字符串。 但如果你这样做,这将解决所有问题:

       function getExtention(fileName){
         var i = fileName.lastIndexOf('.');
         if(i === -1 ) return false;
         return fileName.slice(i)
       }
    

    如果要查找特定的扩展名并知道其长度,可以使用substr

    var file1 = "50.xsl";
    
    if (file1.substr(-4) == '.xsl') {
      // do something
    }
    

    JavaScript参考:

    我在派对上迟到了很多个月,但为了简单起见,我使用了类似的方法

    var fileName=“I.Am.fileName.docx”;
    var nameLen=fileName.length;
    var lastDotPos
    
     return fname.slice((fname.lastIndexOf(".") - 1 >>> 0) + 2);
    
     return fname.slice((Math.max(0, fname.lastIndexOf(".")) || Infinity) + 1);
    
     ""                            -->   ""
     "name"                        -->   ""
     "name.txt"                    -->   "txt"
     ".htpasswd"                   -->   ""
     "name.with.many.dots.myext"   -->   "myext"
    
    function getExtension(path) {
        var basename = path.split(/[\\/]/).pop(),  // extract file name from full path ...
                                                   // (supports `\\` and `/` separators)
            pos = basename.lastIndexOf(".");       // get last position of `.`
    
        if (basename === "" || pos < 1)            // if file name is empty or ...
            return "";                             //  `.` not found (-1) or comes first (0)
    
        return basename.slice(pos + 1);            // extract extension ignoring `.`
    }
    
    console.log( getExtension("/path/to/file.ext") );
    // >> "ext"
    
    return ( filename.indexOf('.') > 0 ) ? filename.split('.').pop().toLowerCase() : 'undefined';
    
    var parts = filename.split('.');
    return (parts.length > 1) ? parts.pop() : '';
    
    (filename.match(/[^\\\/]\.([^.\\\/]+)$/) || [null]).pop()
    
    /path/.htaccess => null
    /dir.with.dot/file => null
    
    fileName.slice(fileName.lastIndexOf('.'))
    
       function getExtention(fileName){
         var i = fileName.lastIndexOf('.');
         if(i === -1 ) return false;
         return fileName.slice(i)
       }
    
    var file1 = "50.xsl";
    
    if (file1.substr(-4) == '.xsl') {
      // do something
    }
    
    string.match(/(.*)\??/i).shift().replace(/\?.*/, '').split('.').pop()
    
    // Example
    // some.url.com/with.in/&ot.s/files/file.jpg?spec=1&.ext=jpg
    // jpg
    
    var file = "hello.txt";
    var ext = (function(file, lio) { 
      return lio === -1 ? undefined : file.substring(lio+1); 
    })(file, file.lastIndexOf("."));
    
    // hello.txt -> txt
    // hello.dolly.txt -> txt
    // hello -> undefined
    // .hello -> hello
    
    /**
     * Extract file extension from URL.
     * @param {String} url
     * @returns {String} File extension or empty string if no extension is present.
     */
    var getFileExtension = function (url) {
        "use strict";
        if (url === null) {
            return "";
        }
        var index = url.lastIndexOf("/");
        if (index !== -1) {
            url = url.substring(index + 1); // Keep path without its segments
        }
        index = url.indexOf("?");
        if (index !== -1) {
            url = url.substring(0, index); // Remove query
        }
        index = url.indexOf("#");
        if (index !== -1) {
            url = url.substring(0, index); // Remove fragment
        }
        index = url.lastIndexOf(".");
        return index !== -1
            ? url.substring(index + 1) // Only keep file extension
            : ""; // No extension found
    };
    
    "https://www.example.com:8080/segment1/segment2/page.html?foo=bar#fragment" --> "html"
    "https://www.example.com:8080/segment1/segment2/page.html#fragment"         --> "html"
    "https://www.example.com:8080/segment1/segment2/.htaccess?foo=bar#fragment" --> "htaccess"
    "https://www.example.com:8080/segment1/segment2/page?foo=bar#fragment"      --> ""
    "https://www.example.com:8080/segment1/segment2/?foo=bar#fragment"          --> ""
    ""                                                                          --> ""
    null                                                                        --> ""
    "a.b.c.d"                                                                   --> "d"
    ".a.b"                                                                      --> "b"
    ".a.b."                                                                     --> ""
    "a...b"                                                                     --> "b"
    "..."                                                                       --> ""
    
    function extension(filename) {
      var r = /.+\.(.+)$/.exec(filename);
      return r ? r[1] : null;
    }
    
    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;
        };
    
    function getExt(filepath){
         return filepath.split("?")[0].split("#")[0].split('.').pop();
    }
    
    getExt("../js/logic.v2.min.js") // js
    getExt("http://example.net/site/page.php?id=16548") // php
    getExt("http://example.net/site/page.html#welcome.to.me") // html
    getExt("c:\\logs\\yesterday.log"); // log
    
    import path from 'path';
    
    console.log(path.extname('abc.txt'));
    
    path.extname('abc.txt').slice(1) // 'txt'
    
    path.extname('abc') // ''