Skip to content

Commit 32e2db9

Browse files
author
Ariel Porporatto
committed
Add new post es_ES
1 parent 349dc48 commit 32e2db9

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
---
2+
layout: post
3+
4+
title: Obtener extensión de archivo
5+
tip-number: 53
6+
tip-username: richzw
7+
tip-username-profile: https://github.com/richzw
8+
tip-tldr: ¿Cómo conseguir la extensión del archivo de manera más eficiente?
9+
10+
categories:
11+
- es_ES
12+
---
13+
14+
### Pregunta: ¿Cómo conseguir la extensión de archivo?
15+
16+
```javascript
17+
var file1 = "50.xsl";
18+
var file2 = "30.doc";
19+
getFileExtension(file1); //returs xsl
20+
getFileExtension(file2); //returs doc
21+
22+
function getFileExtension(filename) {
23+
/*TODO*/
24+
}
25+
```
26+
27+
### Solucion 1: Expresion regular
28+
29+
```js
30+
function getFileExtension1(filename) {
31+
return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename)[0] : undefined;
32+
}
33+
```
34+
35+
### Solucion 2: Metodo `split`
36+
37+
```js
38+
function getFileExtension2(filename) {
39+
return filename.split('.').pop();
40+
}
41+
```
42+
43+
Estas dos soluciones no podían manejar algunos casos extremos, aquí hay otra solución más robusta.
44+
45+
### Solucion 3: Metodos `slice`, `lastIndexOf`
46+
47+
```js
48+
function getFileExtension3(filename) {
49+
return filename.slice((filename.lastIndexOf(".") - 1 >>> 0) + 2);
50+
}
51+
52+
console.log(getFileExtension3('')); // ''
53+
console.log(getFileExtension3('filename')); // ''
54+
console.log(getFileExtension3('filename.txt')); // 'txt'
55+
console.log(getFileExtension3('.hiddenfile')); // ''
56+
console.log(getFileExtension3('filename.with.many.dots.ext')); // 'ext'
57+
```
58+
59+
_¿Como funciona?_
60+
61+
- [String.lastIndexOf()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf) el método devuelve la última aparición del valor especificado (`'.'` en este caso). Devuelve `-1` si no se encuentra el valor.
62+
- Los valores de retorno de `lastIndexOf` para el parámetro `'filename'` y `'.hiddenfile'` son `0` y `-1` respectivamente.[Zero-fill operador de desplazamiento a la derecha (>>>)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#%3E%3E%3E_%28Zero-fill_right_shift%29) transformará `-1` a `4294967295` y `-2` a `4294967294`, aquí es un truco para asegurar el nombre del archivo sin cambios en esos casos extremos.
63+
- [String.prototype.slice()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice) extrae la extensión del índice que se calculó anteriormente. Si el índice es mayor que la longitud del nombre de archivo, el resultado es `""`.
64+
65+
### Comparación
66+
67+
| Solucion | Parametros | Resultados |
68+
| ----------------------------------------- |:-------------------:|:--------:|
69+
| Solucion 1: Expresion regular | ''<br> 'filename' <br> 'filename.txt' <br> '.hiddenfile' <br> 'filename.with.many.dots.ext' | undefined <br> undefined <br> 'txt' <br> 'hiddenfile' <br> 'ext' <br> |
70+
| Solucion 2: Metodo `split` | ''<br> 'filename' <br> 'filename.txt' <br> '.hiddenfile' <br> 'filename.with.many.dots.ext' | '' <br> 'filename' <br> 'txt' <br> 'hiddenfile' <br> 'ext' <br> |
71+
| Solucion 3: Metodos `slice`, `lastIndexOf` | ''<br> 'filename' <br> 'filename.txt' <br> '.hiddenfile' <br> 'filename.with.many.dots.ext' | '' <br> '' <br> 'txt' <br> '' <br> 'ext' <br> |
72+
73+
### Demo de performance
74+
75+
[Here](https://jsbin.com/tipofu/edit?js,console) es la demostración de los códigos anteriores.
76+
77+
[Here](http://jsperf.com/extract-file-extension) es la prueba de rendimiento de esos 3 soluciones.
78+
79+
### Codigo
80+
81+
[How can I get file extensions with JavaScript](http://stackoverflow.com/questions/190852/how-can-i-get-file-extensions-with-javascript)

0 commit comments

Comments
 (0)