Languages
[Edit]
EN

JavaScript - get file extension

3 points
Created by:
Shri
8550

In this article, we would like to show you how to get a file extension in JavaScript.

Practical example:

// ONLINE-RUNNER:browser;

const isSeparator = (value) => value === '/'|| value === '\\' || value === ':';

const getExtension = (path) => {
    for (let i = path.length - 1; i > -1; --i) {
        const value = path[i];
        if (value === '.') {
            if (i > 1) {
                if (isSeparator(path[i - 1])) {
                    return '';
                }
                return path.substring(i + 1);
            }
            return '';
        }
        if (isSeparator(value)) {
            return '';
        }
    }
    return '';
};


// Usage example:

// -- Common:

console.log(getExtension("image.png"));             // png
console.log(getExtension("audio.mp3"));             // mp3
console.log(getExtension("document.pdf"));          // pdf

console.log(getExtension("."));                     //
console.log(getExtension(".."));                    //

console.log(getExtension(".htaccess"));             //
console.log(getExtension(".tar.gz"));               // gz
console.log(getExtension("makefile"));              //

// -- Unix/Linux/macOS:

console.log(getExtension("/path/.htaccess"));       //
console.log(getExtension("/path/.tar.gz"));         // gz
console.log(getExtension("/path/makefile"));        //
console.log(getExtension("/path/example.pdf"));     // pdf

// -- Windows:

console.log(getExtension("C:\\path\\.htaccess"));   //
console.log(getExtension("C:\\path\\.tar.gz"));     // gz
console.log(getExtension("C:\\path\\makefile"));    //
console.log(getExtension("C:\\path\\example.pdf")); // pdf

// -- Also:

console.log(getExtension("C:.htaccess"));           //
console.log(getExtension("C:.tar.gz"));             // gz
console.log(getExtension("C:makefile"));            //
console.log(getExtension("C:example.pdf"));         // pdf

 

See also

  1. TypeScript - get file extension

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join