Skip to main content

JavaScript function to get the file extension from the specified file name. It will return an empty string if you specify an invalid path.

/**
 * Returns the extension of the passed file name.
 * It will return an empty string if you pass an invalid path.
 *
 * @param {String} path The fileName path like '/path/to/file.mp4'
 * @returns {String} The extension in lower case or an empty string if no extension could be found.
 */
function fileExtension(path) {
    if (typeof path === "string") {
        var splitPathRe = /^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/i;
        var pathParts = splitPathRe.exec(path);
        if (pathParts) {
            return pathParts.pop().toLowerCase();
        }
    }
    return "";
}