javascript中的文件扩展名

时间:2012-02-26 06:34:57

标签: javascript filenames

我有一个代码,它带我到文件名的扩展名。它的工作原理是使用匹配“。”的正则表达式:

new_name = e.timeStamp + "_." +
      EscapeHtml (file.name.replace (/ ^. *? \. ([A-zA-Z0-9] +) $ /, "$ 1"));

它适用于这样的简单名称:

name = asdasdasd.mp3

但是当文件名有多个“。”时它不起作用,如:

avi.conn.mp3

如何修改我的代码以应对这些更复杂的案例?

2 个答案:

答案 0 :(得分:5)

只需使用.split()

var components = filename.split('.');
var extension = components[components.length - 1];

答案 1 :(得分:0)

path module of nodejs提供了更好的正则表达式:

var splitDeviceRe = 
    /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?([\\\/])?([\s\S]*?)$/;

// Regex to split the tail part of the above into [*, dir, basename, ext]
var splitTailRe = 
    /^([\s\S]+[\\\/](?!$)|[\\\/])?((?:\.{1,2}$|[\s\S]+?)?(\.[^.\/\\]*)?)$/;

function splitPath(filename) {
    // Separate device+slash from tail
    var result = splitDeviceRe.exec(filename),
        device = (result[1] || '') + (result[2] || ''),
        tail = result[3] || '';
    // Split the tail into dir, basename and extension
    var result2 = splitTailRe.exec(tail),
        dir = result2[1] || '',
        basename = result2[2] || '',
        ext = result2[3] || '';
    return [device, dir, basename, ext];
}

function extname(path) {
    return splitPath(path)[3];
}