Extend RegExp to get the file extension

2019-07-12 19:03发布

问题:

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]
    };
};