我相信这一定很简单,但我在努力...
var regexFileName = /[^\\]*$/; // match filename
var regexFileExtension = /(\w+)$/; // match file extension
function displayUpload() {
var path = $el.val(); //This is a file input
var filename = path.match(regexFileName); // returns file name
var extension = filename[0].match(regexFileExtension); // returns extension
console.log("The filename is " + filename[0]);
console.log("The extension is " + extension[0]);
}上面的函数运行得很好,但我确信它必须能够用一个正则表达式来实现,通过引用.match()方法返回的数组的不同部分来实现。我尝试组合这些正则表达式,但没有成功。
此外,我没有在示例中使用字符串对其进行测试,因为console.log()转义了文件路径中的反斜杠,这让我开始感到困惑:)
发布于 2013-06-25 22:39:48
我认为这是一种更好的方法,因为只匹配有效的目录、文件名和扩展名。并且还对路径、文件名和文件扩展名进行分组。并且也仅适用于空路径的文件名。
^([\w\/]*?)([\w\.]*)\.(\w)$测试用例
the/p0090Aath/fav.min.icon.png
the/p0090Aath/fav.min.icon.html
the/p009_0Aath/fav.m45in.icon.css
fav.m45in.icon.css
favicon.ico输出
[the/p0090Aath/][fav.min.icon][png]
[the/p0090Aath/][fav.min.icon][html]
[the/p009_0Aath/][fav.m45in.icon][css]
[][fav.m45in.icon][css]
[][favicon][ico]https://stackoverflow.com/questions/9001557
复制相似问题