jQuery查找文件扩展名(来自字符串) [英] jQuery find file extension (from string)
问题描述
我想知道jQuery是否有可能基于返回的字符串找到文件扩展名?
I was wondering if it was possible for jQuery to find a file extension based on a returned string?
文件名(字符串)将传递给函数(openFile),我希望该函数根据传递的文件(图像文件或pdf文件)来做不同的事情.
A filename (string) will be passed to a function (openFile) and I wanted that function to do different things based on what file has been passed through, it could be image files or pdf files.
function openFile(file) {
//if .jpg/.gif/.png do something
//if .zip/.rar do something else
//if .pdf do something else
};
我一直在寻找可以找到文件扩展名的东西,但似乎什么也找不到.
I've been looking for something that will find the file's extension but I can't seem to find anything.
推荐答案
这样的事情怎么样.
测试实际示例: http://jsfiddle.net/6hBZU/1 /
假定字符串始终以扩展名结尾
It assumes that the string will always end with the extension:
function openFile(file) {
var extension = file.substr( (file.lastIndexOf('.') +1) );
switch(extension) {
case 'jpg':
case 'png':
case 'gif':
alert('was jpg png gif'); // There's was a typo in the example where
break; // the alert ended with pdf instead of gif.
case 'zip':
case 'rar':
alert('was zip rar');
break;
case 'pdf':
alert('was pdf');
break;
default:
alert('who knows');
}
};
openFile("somestring.png");
编辑:我错误地删除了openFile("somestring.png");
中的部分字符串.已更正.不过,在实时示例"中有它.
EDIT: I mistakenly deleted part of the string in openFile("somestring.png");
. Corrected. Had it in the Live Example, though.
这篇关于jQuery查找文件扩展名(来自字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!