How to extract the extension from a file in Javascript?

There are some cases where I need to capture the extension of a file (that is, a string with file address) to be able to validate the extension via Javascript.

For example of location:

var path = window.location.pathname;
// /foo/bar.html

In case I want to take the html.

There is also the case of treating the extension of a link element, example:

var path = document.querySelector('link').src;
// http://algum.site/css/estilo.css

In case it would have to return the css.

What better way to get this extension?

Considered the cases of URL:

'foo/bar.ext'     // 'ext'
'foo.bar/zaz.ext' // 'ext'
'foo.bar/sem_ext' // ''
'.sem_ext'        // ''
'foo/.sem_ext'    // ''
 20
Author: Comunidade, 2014-02-28

4 answers

To obtain the extension of a file in a practical way use:

var ext = path.split('.').pop();

In case split split the path into an array and pop will remove and return the last element of this array, exactly the extension I'm looking for.

A more accurate version would be:

// Pegar somente a ultima parte, afinal podem ter pastas com . no caminho
var ext = path.split('/').pop();
// se não houver extensão, retorna vazio, se houver retorna a extensão
// sendo que .htaccess é um arquivo escondido e não uma extensão
ext = ext.indexOf('.') < 1 ? '' : ext.split('.').pop();

But it is also possible to do it using lastIndexOf with some mathematical operations to get better performance , example:

function ext(path) {
    var idx = (~-path.lastIndexOf(".") >>> 0) + 2;
    return path.substr((path.lastIndexOf("/") - idx > -3 ? -1 >>> 0 : idx));
}

In this second solution, I used the concept presented by bfavaretto but in a little more performative way.

Explaining the second solution

First we find the position of the ., but since we will use the substr then it is important to know that in the substr if you put a value greater than the string, It will return empty.

Then we use the operator - to turn the value into negative.

Then the operator ~ that will invert the value binary (ex: 0010 turns 1101) this operation is done this way exactly to skip if the file starts with . or if it does not have . in it give a negative value.

With the operator >>> we are moving the positioning in bits within unsigned value (positive), which in case of being negative to 0 will give the largest possible integer minus the value that is being passed in the result of the previous calculation and if it is positive nothing will happen to be unchanged.

Then add 2 to compensate for the operations ~- at the end.

In the next line we have a conditional so that the position of the last / is less than the last point position or if it is a point then, so the less than -3, So apply the same logic to the substr if the value is invalid giving a very large number for it.

 21
Author: Gabriel Gartz, 2017-04-13 12:59:32

The logic for extracting the extension with these requirements is to isolate the last part of the path, and check:

  • if it is blank, it starts with Dot or does not contain Dot: returns ''.
  • otherwise: returns whatever comes after the dot.

You can break the path into arrays, as demonstrated by Gabriel Gartz. is the simplest way .

An option that does not involve arrays, only with string manipulation, is usually more performative . It's about using lastIndexOf to to break the path:

function ext(path) {
    var final = path.substr(path.lastIndexOf('/')+1);
    var separador = final.lastIndexOf('.');
    return separador <= 0 ? '' : final.substr(separador + 1);
}
 9
Author: bfavaretto, 2017-04-13 12:59:36

I like the regular expression approach:

function getExtension(path) {
  var r = /\.([^./]+)$/.exec(path);
  return r && r[1] || '';
}

The regular expression will search for a" dot", followed by any other characters except another dot or a slash. The $ at the end of the expression requires it to be the end of the string.

If this pattern is found in the string, the function will return the 1st capture, i.e. the letters following the last dot. Otherwise, it will return empty string.

Explanation regexper

 6
Author: Fábio Batista, 2014-03-01 22:55:15

As you want to take into account files without extension, as in the case of the ".htaccess", requires a little more Code:

var filename = window.location.pathname.split('/')[window.location.pathname.split('/').length-1].split('.');
var ext = filename[0].length > 0 ? filename[1] : '';
alert(ext)
 3
Author: , 2014-03-01 02:17:22