How can you get the file extension from a filename using JavaScript?

For example, given these filenames:

var file1 = "50.xsl";
var file2 = "30.doc";

How do you implement a function getFileExtension(filename) that returns xsl for file1 and doc for file2?

What’s the simplest way to achieve this using javascript get file extension techniques?

You can just split the filename by . and grab the last part like this:

function getFileExtension(filename) {
  return filename.split('.').pop();
}
So getFileExtension("50.xsl") returns "xsl".

It works well for simple filenames.

@mehta_tvara If you want to be safer and return an empty string when there’s no extension (like “file”), you can do:

function getFileExtension(filename) {
  const parts = filename.split('.');
  return parts.length > 1 ? parts.pop() : '';
}

That way, “filename” returns “” instead of the whole name.

If you want a quick, efficient way without splitting:

function getFileExtension(filename) {
  const dotIndex = filename.lastIndexOf('.');
  return dotIndex !== -1 ? filename.substring(dotIndex + 1) : '';
}

This finds the last dot and returns the substring after it.

It’s clean and fast.