Onjsdev

Share


How to get the extension of a file in javascript

How to Get Extension Of A File In JavaScript


By onjsdev

Nov 5th, 2023

When working with files in JavaScript, you may need to determine the file extension. The file extension is the part of a file's name that comes after the last dot, like ".txt" in "document.txt".

Here, we'll explore different ways to extract the file extension using JavaScript.

Using the split() Function

To get a file extension from a file path or name, you can use the split() function. The idea is to split the string at the dot (.) and get the last part, which is the extension.

Here's how you can do it:

function getFileExtension(filePath) {
  return filePath.split('.').pop();
}

// Example usage
const filename = 'my_document.pdf';
const extension = getFileExtension(filename);
console.log(extension); // Output: pdf

In this code, we define a function called getFileExtension that takes a filePath parameter. We split the filePath string using the dot character as the separator and use pop() to get the last part, which is the file extension.

Using Regular Expressions

Regular expressions are powerful for matching patterns in strings, including file extensions. You can use regular expressions in JavaScript to extract the file extension.

Here's an example:

function getFileExtension(filePath) {
  const regex = /(?:\.([^.]+))?$/;
  const extension = regex.exec(filePath)[1];
  return extension;
}

// Example usage
const filename = 'my_document.pdf';
const extension = getFileExtension(filename);
console.log(extension);
// Output: pdf

In this code, we define a regular expression pattern that captures characters after the last dot (.) in the string. We use exec() to match the regular expression against the filePath string and get the captured group at index 1, which is the file extension.

Using the path Module (Nodejs)

If you work with file paths in a Node.js environment, you can use the built-in path module to extract file extensions. The path module provides useful functions for working with file paths, including extname(), which gives you the extension of a file path.

Here's an example:

const path = require('path');

function getFileExtension(filePath) {
  return path.extname(filePath).slice(1);
}

// Example usage
const filename = 'my_document.pdf';
const extension = getFileExtension(filename);
console.log(extension);
// Output: pdf

In this code, we require the path module and define the getFileExtension function. We use path.extname() to directly obtain the file extension and then use slice(1) to remove the dot.

Conclusion

In this article, we explored three methods to get the extension a file. The first method uses the split() function, the second employs regular expressions, and the third, in a Nodejs environment, uses the path module's extname() function.

Thank you for reading!