Extend RegExp to get the file extension

折月煮酒 提交于 2019-12-11 03:32:41

问题


I know, there're already a lot of RegExp based solutions, however I couldn't find one that fits to my needs.

I've the following function to get the parts of an URL, but I also need the file extension.

var getPathParts = function(url) {
    var m = url.match(/(.*)[\/\\]([^\/\\]+)\.\w+$/);
    return {
        path: m[1],
        file: m[2]
    };
};

var url = 'path/to/myfile.ext';
getPathParts(url); // Object {path: "path/to", file: "myfile"} 

I'm not very familiar with regex, maybe you can extend this given regexp, to get the file-extension too?

Best way would, if the 3rd (4th) value the file extension contains. E.g.:

return {
    path: m[1],
    file: m[2],
    ext: m[3]
};

回答1:


Just add a capturing group to get the last \w+ :

var getPathParts = function(url) {
    var m = url.match(/(.*)[\/\\]([^\/\\]+)\.(\w+)$/);
    return {
        path: m[1],
        file: m[2],
        ext: m[3]
    };
};


来源:https://stackoverflow.com/questions/14750913/extend-regexp-to-get-the-file-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!