看代码:
var file1 = "50.xsl";
var file2 = "30.doc";
getFileExtension(file1); //returns xsl
getFileExtension(file2); //returns doc
function getFileExtension(filename) {
/*TODO*/
}
看代码:
var file1 = "50.xsl";
var file2 = "30.doc";
getFileExtension(file1); //returns xsl
getFileExtension(file2); //returns doc
function getFileExtension(filename) {
/*TODO*/
}
当前回答
// 获取文件后缀名 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"));
其他回答
在path模块中有一个标准库函数:
import path from 'path';
console.log(path.extname('abc.txt'));
输出:
. txt
所以,如果你只想要格式:
path.extname('abc.txt').slice(1) // 'txt'
如果没有扩展名,函数将返回一个空字符串:
path.extname('abc') // ''
如果使用Node,则path是内置的。如果你的目标是浏览器,那么Webpack将为你捆绑一个路径实现。如果你的目标浏览器没有Webpack,那么你可以手动包含path-browserify。
没有理由进行字符串分割或正则表达式。
对于大多数应用程序,一个简单的脚本,如
return /[^.]+$/.exec(filename);
会工作得很好(由汤姆提供)。然而,这并非万无一失。如果提供了以下文件名,它将不起作用:
image.jpg?foo=bar
这可能有点过分,但我建议使用这样的url解析器来避免由于不可预测的文件名而导致的失败。
使用这个特定的函数,你可以得到这样的文件名:
var trueFileName = parse_url('image.jpg?foo=bar').file;
这将输出“image.jpg”,不带url变量。然后您就可以获取文件扩展名了。
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
function getExt(filename)
{
var ext = filename.split('.').pop();
if(ext == filename) return "";
return ext;
}
我相信将来会有人缩小和/或优化我的代码。但是,到目前为止,我有200%的信心,我的代码在每一个独特的情况下工作(例如,只有文件名,相对,根相对,和绝对URL的,片段#标签,与查询?字符串,以及任何你可能决定扔给它的东西),完美无缺,精确到极点。
为了证明,请访问:https://projects.jamesandersonjr.com/web/js_projects/get_file_extension_test.php
这是JSFiddle: https://jsfiddle.net/JamesAndersonJr/ffcdd5z3/
不要过于自信,或者自吹自擂,但我还没有看到任何代码块的这个任务(找到“正确的”文件扩展名,在电池不同的函数输入参数),工作得很好。
注意:按照设计,如果给定的输入字符串不存在文件扩展名,它只返回一个空白字符串“”,而不是错误,也不是错误消息。
它有两个参数: 字符串:fileNameOrURL(自解释) 布尔值:showUnixDotFiles(是否显示以点“。”开头的文件)
注(2):如果你喜欢我的代码,一定要把它添加到你的js库中,和/或repo库中,因为我努力完善它,浪费它将是一种耻辱。所以,废话不多说,下面是:
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;
};
享受吧!不客气!: