Getting a file extension with JavaScript

For a current project, I needed to get the extension of a file being given it’s full path. In C#, you’d do something like this:

var extension = Path.GetExtension(path);

Unfortunately, we have no such possibility in JavaScript. Fortunately, writing a function returning the extension in JavaScript is not that difficult.

First you need to get the file name from the full path (basically getting rid of all parent directories in the path). In order to do this you have to also consider that you could either have a slash or a backslash as separator in the path.

The file name is basically, the last part of the path when you split it with the file path separator. This means you just need to use a split and a pop:

var filename = path.split('/').pop(); // when using slash as a file path separator

var filename = path.split('\\').pop(); // when using backslash as a file path separator

In order to handle both, you just need to do it twice:

var filename = path.split('\\').pop().split('/').pop();

It doesn’t really matter in which order you do it. If you use slashes, the first split/pop combination will not do anything. If you use backslashes, the second one will not do anything.

Getting the file name without path information is important because we’ll be searching for the extension based on dots in the path. If one of the parent directories does contain a dot, it will return a wrong results, so it’s safer to first get the file name without path information and then get the file extension.

Now we have the file name (without full path information), we need to extract the extension.

Let’s first look at which results we expect in different cases:

  • if the input name isĀ an empty string, the returned extension should be an empty string as well
  • if the input name is does not contain any dots, the returned extension should be an empty string
  • if the input name contains only one dot and it’s the first character of the file name (e.g. .htpasswd), the returned extension should be an empty string
  • if the input name starts with a dot but contains another dot (e.g. .htpasswd.sav), the returned extension should be the part after the last dot
  • in general if the name contains any dots which are not at the beginning of the file, the returned extension should be the part after the last dot

You can get the index of the last dot in the file name using:

filename.lastIndexOf(".")

This will return -1 if no dot is present in the name. In this case, there is no extension and we can return an empty string:

var lastIndex = filename.lastIndexOf(".");
if (lastIndex < 0) return "";

Actually, even if it returns 0, it means that the file name starts with a dot and contains no further dots. In this case we also want to return an empty string:

var lastIndex = filename.lastIndexOf(".");
if (lastIndex < 1) return "";

In other cases (i.e. when we have at least one dot which is not at the beginning of the name), we want to exclude everything until the dot (including it) and return the rest:

var lastIndex = filename.lastIndexOf(".");
if (lastIndex < 1) return "";
return filename.substr(lastIndex + 1);

So the complete function to get the file extension from an arbitrary file path is:

function getFilePathExtension(path) {
	var filename = path.split('\\').pop().split('/').pop();
	var lastIndex = filename.lastIndexOf(".");
	if (lastIndex < 1) return "";
	return filename.substr(lastIndex + 1);
}

Now let’s test it a little bit and check that we do get the expected results:

console.log(getFilePathExtension(""));
console.log(getFilePathExtension("name"));
console.log(getFilePathExtension("name.ext"));
console.log(getFilePathExtension(".name"));
console.log(getFilePathExtension(".name.ext"));
console.log(getFilePathExtension("name.with.a.few.dots.ext"));
console.log(getFilePathExtension("/path/with/.a/few/dots"));
console.log(getFilePathExtension("/path/with/.a/few/.dots"));
console.log(getFilePathExtension("/path/with/.a/few/.dots/name.with.a.few.dots.ext"));

As expected the 4 tests where the name ends with “.ext” will return ext. The others will return an empty string.

You can make the function above even a little bit compacter (but less readable) by using Infinity as index in case the index returned is 0 or less. This is done by using:

  1. the Math.max function so that we get 0 whether lastIndexOf returns -1 or 0
  2. the fact that 0 is evaluated as false
  3. the fact that substr will return an empty string if the provided index is higher than the index of the last character
  4. the fact that Infinity + 1 is still higher than the index of the last character

So the compacter code looks like this:

function getFilePathExtension(path) {
	var filename = path.split('\\').pop().split('/').pop();
	return filename.substr(( Math.max(0, filename.lastIndexOf(".")) || Infinity) + 1);
}

 

2 thoughts on “Getting a file extension with JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *