To get the extension of a file in a practical way:
var ext = path.split('.').pop();
In this case, split
divided the path into an array and pop
will remove and return the last element of this array, just 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 you can also do this 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 .
, but since we're going to use substr
then it's important to know that in substr
if you put a value greater than string , it goes return empty.
Then we use the -
operator to turn the value into negative.
Then the ~
operator that will invert the binary value (ex: 0010
turns 1101
) this operation is done exactly to skip if the file starts with .
or if it does not have .
give it a negative value.
With the >>>
operator, we are moving the positioning in bits into unsigned (positive) value, which in the case of being negative to 0 will give the largest possible integer minus the value being passed in the result of the previous calculation and if it is positive nothing will happen to be changed.
Then add 2 to compensate for ~-
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 next, 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.