看代码:

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

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

当前回答

我已经晚了很多个月,但为了简单起见,我使用了这样的东西

var 文件名 = “I.Am.文件名.docx”; var nameLen = fileName.length; var lastDotPos = fileName.lastIndexOf(“.”); var 文件名子 = 假; if(lastDotPos === -1) { 文件名子 = 假; } 还 { 如果希望“.”也保留,请删除 +1 fileNameSub = fileName.substr(lastDotPos + 1, nameLen); } document.getElementById(“showInMe”).innerHTML = fileNameSub; <div id=“showInMe”></div>

其他回答

使用reduce和数组解构来获取文件名和扩展名:

Var STR = "filename.with_dot.png"; Var [filename, extension] = str.split('.')。Reduce ((acc, val, i, arr) => (i == arr。长度- 1)?(acc [0] .substring (1), val]: [[acc [0], val] . join ('.')], []) console.log({文件名,扩展});

有更好的缩进:

var str = "filename.with_dot.png";
var [filename, extension] = str.split('.')
   .reduce((acc, val, i, arr) => (i == arr.length - 1) 
       ? [acc[0].substring(1), val] 
       : [[acc[0], val].join('.')], [])


console.log({filename, extension});

// {
//   "filename": "filename.with_dot",
//   "extension": "png"
// }

Code

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

Test

注意,在没有查询的情况下,片段可能仍然存在。

"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"
"..."                                                                       --> ""

JSLint

0的警告。

var extension = fileName.substring(fileName.lastIndexOf('.')+1);

如果你正在寻找一个特定的扩展名,并且知道它的长度,你可以使用substr:

var file1 = "50.xsl";

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

JavaScript参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr

// 获取文件后缀名 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"));