Clue Mediator

How to get File Extension using JavaScript

📅May 3, 2022

Today you will learn how to get file extension from given file name using JavaScript. Here we will see two different methods to get the file extension. You may need it during File Upload or Preview Image.

Checkout more articles on JavaScript

Way to get file extension using JavaScript

  1. Using split() and pop() method
  2. Using substring() and lastIndexOf() method

1. Using split() and pop() method

Let’s use the split() and pop() methods to split the string and get the last element.

// get file extension
function getFileExtension(filename){
    const extension = filename.split('.').pop();
    return extension;
}

const res1 = getFileExtension('index.html');
console.log(res1); // Output: html

const res2 = getFileExtension('index.txt');
console.log(res2); // Output: txt

2. Using substring() and lastIndexOf() method

In this second method, we’ll use the substring() and lastIndexOf() to get the file extension.

// get file extension
function getFileExtension(filename){
    const extension = filename.substring(filename.lastIndexOf('.') + 1, filename.length);
    return extension;
}

const res1 = getFileExtension('index.html');
console.log(res1); // Output: html

const res2 = getFileExtension('index.txt');
console.log(res2); // Output: txt

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂