Back to JavaScript
2026-01-075 min read

JavaScript Program to Get File Extension

Learn JavaScript Program to Get File Extension step by step with clear examples and exercises.

Title: JavaScript Program to Get File Extension

Why This Matters

Understanding how to get a file extension is crucial in programming for various reasons. Firstly, it helps in identifying the type of a file, which can be useful when dealing with different file formats. Secondly, it plays an essential role in developing applications that handle multiple types of files, such as image viewers or document editors. Lastly, knowing how to get a file extension can help you debug issues related to incorrect file handling.

In addition, being able to extract the file extension from a filename can be useful when performing operations like filtering, sorting, or organizing files based on their types.

Prerequisites

Before diving into the JavaScript program to get the file extension, you should have a basic understanding of the following topics:

  • Variables and data types in JavaScript
  • String manipulation methods in JavaScript (e.g., indexOf, lastIndexOf, substring, split)
  • Regular expressions (optional but recommended)

Understanding Regular Expressions

Regular expressions (regex) are powerful tools used for pattern matching within strings. They can be helpful when dealing with file extensions, as they allow you to easily match and extract patterns from filenames. If you're not familiar with regex, we recommend reading up on the topic before proceeding.

Core Concept

To get the file extension in JavaScript, we can use several methods:

  1. Using split() method along with pop() method or a regular expression.
  2. Manipulating the filename using a loop and checking for the dot position.
  3. Utilizing the path module (for Node.js applications).

In this lesson, we will focus on the first method: using the split() method along with pop() method or a regular expression. The split() method splits a string into an array of substrings based on a specified separator. In this case, we will use the dot (.) as our separator to split the filename and get the extension.

Using split() and pop()

Here's a simple JavaScript function that gets the file extension using both methods:

function getFileExtension(filename) {
// Split the filename into an array using the dot as separator
const extension = filename.split('.');

// The extension is the last element in the array, so we use pop() to remove it and return it
return extension.pop();
}

Using regular expressions (getFileExtensionRegex())

We can also use regular expressions to match the pattern of a filename with its extension and extract the extension using the matched group:

function getFileExtensionRegex(filename) {
// Use a regular expression to match the pattern of a filename with its extension
const regex = /(\..*)?$/;

// Extract the matched group (i.e., the file extension) from the filename
const extension = filename.match(regex)[1];

// If there's no match, return an empty string
if (!extension) return '';

// Return the extracted file extension
return extension;
}

Worked Example

Let's test our functions with some examples:

Using split() and pop()

  1. Test case: example.txt
const filename = 'example.txt';
console.log(getFileExtension(filename)); // Output: txt
  1. Test case: image001.jpg
const filename = 'image001.jpg';
console.log(getFileExtension(filename)); // Output: jpg

Using regular expressions (getFileExtensionRegex())

  1. Test case: example.txt
const filename = 'example.txt';
console.log(getFileExtensionRegex(filename)); // Output: txt
  1. Test case: image001.jpg
const filename = 'image001.jpg';
console.log(getFileExtensionRegex(filename)); // Output: jpg

Common Mistakes

  1. ### Forgetting to handle empty filenames or no extension cases

To avoid issues when dealing with empty filenames or files without extensions, you can add a check before splitting the filename or using regular expressions:

function getFileExtension(filename) {
// If there's no dot in the filename, return an empty string
if (!filename.includes('.')) return '';

// Split the filename into an array using the dot as separator
const extension = filename.split('.');

// The extension is the last element in the array, so we use pop() to remove it and return it
return extension.pop();
}

function getFileExtensionRegex(filename) {
// If there's no match (i.e., no extension), return an empty string
const match = filename.match(/\..*/);
if (!match) return '';

// Extract the matched group (i.e., the file extension) from the filename
const extension = match[0];

// Remove any preceding dots before returning the extension
return extension.replace(/^\./, '');
}
  1. ### Not accounting for multiple dots in filenames

To handle cases where a filename contains multiple dots (e.g., my.file.name), you can modify the function to only consider the last dot:

function getFileExtension(filename) {
// Find the index of the last dot in the filename
const lastDotIndex = filename.lastIndexOf('.');

// If there's no dot in the filename, return an empty string
if (lastDotIndex === -1) return '';

// Extract the extension from the filename starting from the index of the last dot to the end
const extension = filename.substring(lastDotIndex);

// Remove any preceding dots before returning the extension
return extension.replace(/^\./, '');
}

Practice Questions

  1. Write a JavaScript function that checks if a given filename has an extension of .pdf.
  1. Modify the getFileExtension function to handle filenames with multiple dots and return the last extension (e.g., for my.file.name.extension, it should return extension).
  1. Write a JavaScript function that uses regular expressions to validate if a given filename has a valid file extension (e.g., only allowing extensions like .txt, .jpg, .png, etc.).
  1. ### What if the filename doesn't have an extension but contains a dot for another reason?

In such cases, our functions will still return the last occurrence of the dot as the file extension. To handle this situation, you can add additional checks to ensure that the returned extension is valid or expected based on your application's requirements.

FAQ

### What if the filename doesn't have an extension?

In that case, our functions will return an empty string, which is a valid result indicating no extension was found. You can add additional checks to handle such cases according to your application's requirements.

### Can I use other methods to get the file extension in JavaScript?

Yes, there are alternative ways to get the file extension in JavaScript. For example, you could use the path module if you're working with Node.js or manipulate the filename using a loop and checking for the dot position. However, the methods presented in this lesson provide a simple and efficient solution that can be easily understood and implemented.

### How do I handle filenames with multiple extensions (e.g., myfile.txt.html)?

To handle such cases, you can modify the function to consider only the last extension by finding the index of the last dot and extracting the substring from that index to the end of the filename. This will ensure that you get the last extension in cases where a filename has multiple extensions.

### How do I handle filenames with leading or trailing spaces?

To handle filenames with leading or trailing spaces, you can trim the whitespace from the filename before performing any operations on it using the trim() method. This ensures that the function works correctly regardless of whether the filename has leading or trailing spaces.

JavaScript Program to Get File Extension | JavaScript | XQA Learn