To get the file extension in a practical way use:
var ext = path.split('.').pop();
In case the split
divided the path into an array and the 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 obtain best 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 how will we 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.
So we use the operator -
to turn the value into negative.
Then the operator ~
reversing the binary value (ex: 0010
flipped 1101
) this operation is done in this way exactly to jump if the file starts with .
or if you don’t have .
in it give a negative value.
With the operator >>>
we are moving the positioning in bits within unsigned value (positive), which in the case of being negative to 0 will give the largest possible integer less the value that is being passed in the result of the previous calculation and if it is positive nothing will happen be changed.
Then add 2 to compensate for operations ~-
in the end.
In the next line we have a conditional one so that the position of the last /
is less than the last point position or if it is a point then less than -3, so apply the same logic to the substr
if the value is invalid giving a very large number to him.
It was a bit of an explanation, I think I could open questions and answers of these operations here in stackoverflow, because they should interest other programmers.
– Gabriel Gartz
We can open, but I thought it was good size, your answer is quite complete now! If I could, I would vote again :)
– bfavaretto
The size of the answer is not necessarily a problem. I prefer a big but complete answer to a simple and that lets some information escape.
– Kazzkiq