¿Cómo puedo obtener extensiones de archivo con JavaScript?


Ver código:

var file1 = "50.xsl";
var file2 = "30.doc";
getFileExtension(file1); //returns xsl
getFileExtension(file2); //returns doc

function getFileExtension(filename) {
    /*TODO*/
}
Author: Ghoul Fool, 2008-10-10

30 answers

Más reciente Edición: Muchas cosas han cambiado desde que esta pregunta se publicó inicialmente-hay mucha información realmente buena en la respuesta revisada de wallacer así como el excelente desglose de VisioN


Editar: Solo porque esta es la respuesta aceptada; la respuesta de wallacer es de hecho mucho mejor:

return filename.split('.').pop();

Mi vieja respuesta:

return /[^.]+$/.exec(filename);

Debería hacerlo.

Editar: En respuesta al comentario de PhiLho, use algo como:

return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;
 579
Author: Tom,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:29
return filename.split('.').pop();

Manténgalo simple:)

Editar:

Esta es otra solución no regex que creo que es más eficiente:

return filename.substring(filename.lastIndexOf('.')+1, filename.length) || filename;

Hay algunos casos de esquina que son mejor manejados por la respuesta de VisioN a continuación, particularmente los archivos sin extensión (.htaccess, etc. incluidos).

Es muy eficiente, y maneja casos de esquina de una manera posiblemente mejor devolviendo "" en lugar de la cadena completa cuando no hay punto o ninguna cadena antes del punto. Es un solución muy bien elaborada, aunque difícil de leer. Mételo en tu libreta de ayudantes y úsalo.

Edición antigua:

Una implementación más segura si vas a encontrar archivos sin extensión, o archivos ocultos sin extensión (ver el comentario de VisióN a la respuesta de Tom más arriba) sería algo en estas líneas

var a = filename.split(".");
if( a.length === 1 || ( a[0] === "" && a.length === 2 ) ) {
    return "";
}
return a.pop();    // feel free to tack .toLowerCase() here if you want

Si a.length es uno, es un archivo visible sin extensión ie. file

Si a[0] === "" y a.length === 2 es un archivo oculto sin extensión ie. .htaccess

Espero que esto ayude a aclarar los problemas con los casos un poco más complejos. En términos de rendimiento, creo que esta solución es un poco más lenta que regex en la mayoría de los navegadores. Sin embargo, para los propósitos más comunes este código debería ser perfectamente utilizable.

 688
Author: wallacer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-28 09:51:59

La siguiente solución es rápida y corta suficiente para usar en operaciones masivas y guardar bytes adicionales:

 return fname.slice((fname.lastIndexOf(".") - 1 >>> 0) + 2);

Aquí hay otra solución universal no regexp de una línea:

 return fname.slice((Math.max(0, fname.lastIndexOf(".")) || Infinity) + 1);

Ambos funcionan correctamente con nombres que no tienen extensión (por ejemplo, myfile) o que comienzan con . punto (por ejemplo, .htaccess):

 ""                            -->   ""
 "name"                        -->   ""
 "name.txt"                    -->   "txt"
 ".htpasswd"                   -->   ""
 "name.with.many.dots.myext"   -->   "myext"

Si te importa la velocidad, puedes ejecutar el parámetro y compruebe que las soluciones proporcionadas son el más rápido, mientras que el corto es tremendamente rápido:

Comparación de velocidad

Cómo funciona el corto:

  1. String.lastIndexOf method devuelve la última posición de la subcadena (es decir, ".") en la cadena dada (es decir, fname). Si la subcadena no se encuentra, el método devuelve -1.
  2. Las posiciones "inaceptables" de punto en el nombre del archivo son -1 y 0, que respectivamente se refieren a nombres sin extensión (por ejemplo, "name") y a nombres que comienzan con punto (por ejemplo, ".htaccess").
  3. Operador de turno derecho de relleno cero (>>>) si se usa con cero afecta a los números negativos que transforman -1 a 4294967295 y -2 a 4294967294, lo que es útil para mantener el nombre del archivo sin cambios en los casos de borde (una especie de truco aquí).
  4. String.prototype.slice extrae la parte del nombre del archivo de la posición que se calculó como se describe. Si el número de posición es mayor que la longitud de la cadena, el método devuelve "".

Si desea una solución más clara que funcione de la misma manera (además de con soporte adicional de ruta completa), verifique la siguiente versión extendida. Esta solución será más lenta que las anteriores, pero es mucho más fácil de entender.

function getExtension(path) {
    var basename = path.split(/[\\/]/).pop(),  // extract file name from full path ...
                                               // (supports `\\` and `/` separators)
        pos = basename.lastIndexOf(".");       // get last position of `.`

    if (basename === "" || pos < 1)            // if file name is empty or ...
        return "";                             //  `.` not found (-1) or comes first (0)

    return basename.slice(pos + 1);            // extract extension ignoring `.`
}

console.log( getExtension("/path/to/file.ext") );
// >> "ext"

Las tres variantes deberían funcionar en cualquier navegador web del lado del cliente y también pueden usarse en el código NodeJS del lado del servidor.

 237
Author: VisioN,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-04 10:00:03
function getFileExtension(filename)
{
  var ext = /^.+\.([^.]+)$/.exec(filename);
  return ext == null ? "" : ext[1];
}

Probado con

"a.b"     (=> "b") 
"a"       (=> "") 
".hidden" (=> "") 
""        (=> "") 
null      (=> "")  

También

"a.b.c.d" (=> "d")
".a.b"    (=> "b")
"a..b"    (=> "b")
 23
Author: PhiLho,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-07 00:53:52
function getExt(filename)
{
    var ext = filename.split('.').pop();
    if(ext == filename) return "";
    return ext;
}
 18
Author: Dima,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-26 20:45:28
var extension = fileName.substring(fileName.lastIndexOf('.')+1);
 12
Author: Pono,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-23 17:23:37
var parts = filename.split('.');
return parts[parts.length-1];
 8
Author: Randy Sugianto 'Yuku',
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-10 11:18:40
function file_get_ext(filename)
    {
    return typeof filename != "undefined" ? filename.substring(filename.lastIndexOf(".")+1, filename.length).toLowerCase() : false;
    }
 8
Author: Joe Scylla,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-10 13:53:57

Código

/**
 * Extract file extension from URL.
 * @param {String} url
 * @returns {String} File extension or empty string if no extension is present.
 */
var getFileExtension = function (url) {
    "use strict";
    if (url === null) {
        return "";
    }
    var index = url.lastIndexOf("/");
    if (index !== -1) {
        url = url.substring(index + 1); // Keep path without its segments
    }
    index = url.indexOf("?");
    if (index !== -1) {
        url = url.substring(0, index); // Remove query
    }
    index = url.indexOf("#");
    if (index !== -1) {
        url = url.substring(0, index); // Remove fragment
    }
    index = url.lastIndexOf(".");
    return index !== -1
        ? url.substring(index + 1) // Only keep file extension
        : ""; // No extension found
};

Prueba

Observe que en ausencia de una consulta, el fragmento podría estar todavía presente.

"https://www.example.com:8080/segment1/segment2/page.html?foo=bar#fragment" --> "html"
"https://www.example.com:8080/segment1/segment2/page.html#fragment"         --> "html"
"https://www.example.com:8080/segment1/segment2/.htaccess?foo=bar#fragment" --> "htaccess"
"https://www.example.com:8080/segment1/segment2/page?foo=bar#fragment"      --> ""
"https://www.example.com:8080/segment1/segment2/?foo=bar#fragment"          --> ""
""                                                                          --> ""
null                                                                        --> ""
"a.b.c.d"                                                                   --> "d"
".a.b"                                                                      --> "b"
".a.b."                                                                     --> ""
"a...b"                                                                     --> "b"
"..."                                                                       --> ""

JSLint

0 Advertencias.

 6
Author: Jack,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-10 02:16:25

Rápido y funciona correctamente con caminos

(filename.match(/[^\\\/]\.([^.\\\/]+)$/) || [null]).pop()

Algunos casos extremos

/path/.htaccess => null
/dir.with.dot/file => null

Las soluciones que usan split son lentas y las soluciones con lastIndexOf no manejan casos extremos.

 5
Author: mrbrdo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-18 18:24:00

Prueba esto:

function getFileExtension(filename) {
  var fileinput = document.getElementById(filename);
  if (!fileinput)
    return "";
  var filename = fileinput.value;
  if (filename.length == 0)
    return "";
  var dot = filename.lastIndexOf(".");
  if (dot == -1)
    return "";
  var extension = filename.substr(dot, filename.length);
  return extension;
}
 4
Author: Edward,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-07 10:46:04

Solo quería compartir esto.

fileName.slice(fileName.lastIndexOf('.'))

Aunque esto tiene una desventaja que los archivos sin extensión devolverán la última cadena. pero si lo haces esto arreglará todo :

   function getExtention(fileName){
     var i = fileName.lastIndexOf('.');
     if(i === -1 ) return false;
     return fileName.slice(i)
   }
 4
Author: Hussein Nazzal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-04 16:08:09
return filename.replace(/\.([a-zA-Z0-9]+)$/, "$1");

Editar: Extrañamente (o tal vez no lo es) el $1 en el segundo argumento del método replace no parece funcionar... Disculpe....

 3
Author: p4bl0,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-10 11:20:11

Acabo de darme cuenta de que no es suficiente poner un comentario en la respuesta de p4bl0, aunque la respuesta de Tom claramente resuelve el problema:

return filename.replace(/^.*?\.([a-zA-Z0-9]+)$/, "$1");
 3
Author: roenving,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-10 14:14:10

Para la mayoría de las aplicaciones, un script simple como

return /[^.]+$/.exec(filename);

Funcionaría bien (según lo proporcionado por Tom). Sin embargo, esto no es a prueba de tontos. No funciona si se proporciona el siguiente nombre de archivo:

image.jpg?foo=bar

Puede ser un poco exagerado, pero sugeriría usar un analizador de url como este para evitar errores debido a nombres de archivo impredecibles.

Usando esa función en particular, podría obtener el nombre del archivo de esta manera:

var trueFileName = parse_url('image.jpg?foo=bar').file;

Esto producirá "imagen.jpg" sin la url vars. Entonces usted es libre de tomar la extensión de archivo.

 3
Author: Justin Bull,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-04-07 16:18:35
function func() {
  var val = document.frm.filename.value;
  var arr = val.split(".");
  alert(arr[arr.length - 1]);
  var arr1 = val.split("\\");
  alert(arr1[arr1.length - 2]);
  if (arr[1] == "gif" || arr[1] == "bmp" || arr[1] == "jpeg") {
    alert("this is an image file ");
  } else {
    alert("this is not an image file");
  }
}
 3
Author: Jim Blackler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-12 09:09:34
function extension(fname) {
  var pos = fname.lastIndexOf(".");
  var strlen = fname.length;
  if (pos != -1 && strlen != pos + 1) {
    var ext = fname.split(".");
    var len = ext.length;
    var extension = ext[len - 1].toLowerCase();
  } else {
    extension = "No extension found";
  }
  return extension;
}

/ / uso

Extensión ('file.jpeg")

Siempre devuelve la extensión cas inferior para que pueda comprobarla en el cambio de campo obras para:

Archivo.JpEg

Archivo (sin extensión)

Archivo. (noextension)

 3
Author: Jim Blackler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-12 09:10:28

Si está buscando una extensión específica y conoce su longitud, puede usar substr :

var file1 = "50.xsl";

if (file1.substr(-4) == '.xsl') {
  // do something
}

Referencia de JavaScript: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr

 3
Author: Jenny O'Reilly,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-25 10:23:11

Llego muchas lunas tarde a la fiesta, pero por simplicidad uso algo como esto

var fileName = "I.Am.FileName.docx";
var nameLen = fileName.length;
var lastDotPos = fileName.lastIndexOf(".");
var fileNameSub = false;
if(lastDotPos === -1)
{
    fileNameSub = false;
}
else
{
    //Remove +1 if you want the "." left too
    fileNameSub = fileName.substr(lastDotPos + 1, nameLen);
}
document.getElementById("showInMe").innerHTML = fileNameSub;
<div id="showInMe"></div>
 3
Author: DzSoundNirvana,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-04 18:19:50

Una solución de una línea que también tendrá en cuenta los parámetros de consulta y cualquier carácter en la url.

string.match(/(.*)\??/i).shift().replace(/\?.*/, '').split('.').pop()

// Example
// some.url.com/with.in/&ot.s/files/file.jpg?spec=1&.ext=jpg
// jpg
 2
Author: Labithiotis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-20 17:18:29

La respuesta de Wallacer es buena, pero se necesita una comprobación más.

Si el archivo no tiene extensión, usará filename como extensión que no es buena.

Prueba este:

return ( filename.indexOf('.') > 0 ) ? filename.split('.').pop().toLowerCase() : 'undefined';
 1
Author: crab,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-06 02:24:06

No olvide que algunos archivos no pueden tener extensión, así que:

var parts = filename.split('.');
return (parts.length > 1) ? parts.pop() : '';
 1
Author: Tamás Pap,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-13 09:32:20

Esta solución simple

function extension(filename) {
  var r = /.+\.(.+)$/.exec(filename);
  return r ? r[1] : null;
}

Pruebas

/* tests */
test('cat.gif', 'gif');
test('main.c', 'c');
test('file.with.multiple.dots.zip', 'zip');
test('.htaccess', null);
test('noextension.', null);
test('noextension', null);
test('', null);

// test utility function
function test(input, expect) {
  var result = extension(input);
  if (result === expect)
    console.log(result, input);
  else
    console.error(result, input);
}

function extension(filename) {
  var r = /.+\.(.+)$/.exec(filename);
  return r ? r[1] : null;
}
 1
Author: Vitim.us,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-28 18:18:33

Estoy seguro de que alguien puede, y lo hará, minificar y/u optimizar mi código en el futuro. Pero, a partir de ahora mismo , estoy 200% seguro de que mi código funciona en cada situación única (por ejemplo, solo con el nombre de archivo , con relativo, url raíz relativa, y absoluta, con fragmento # etiquetas, con consulta ? cuerdas, y cualquier otra cosa que usted puede decidir lanzar en él), sin problemas, y con precisión de punta.

Como prueba, visita: https://projects.jamesandersonjr.com/web/js_projects/get_file_extension_test.php

Aquí está el JSFiddle: https://jsfiddle.net/JamesAndersonJr/ffcdd5z3 /

No quiero ser demasiado confiado, ni tocar mi propia trompeta, pero no he visto ningún bloque de código para esta tarea (encontrar la extensión de archivo 'correcta', en medio de una batería de diferentes function argumentos de entrada) que funcione tan bien como esto.

Note: By design, if a la extensión de archivo no existe para la cadena de entrada dada, simplemente devuelve una cadena en blanco "", no un error, ni un mensaje de error.

Se necesitan dos argumentos:

  • String: fileNameOrURL (autoexplicativo)

  • Booleano: showUnixDotFiles (Si mostrar o no los archivos que comienzan con un punto ".")

Nota (2): Si te gusta mi código, asegúrese de agregarlo a su biblioteca js, y / o repo, porque trabajé duro en perfeccionarlo, y sería una pena desperdiciarlo. Así que, sin más preámbulos, aquí está:

function getFileExtension(fileNameOrURL, showUnixDotFiles)
    {
        /* First, let's declare some preliminary variables we'll need later on. */
        var fileName;
        var fileExt;

        /* Now we'll create a hidden anchor ('a') element (Note: No need to append this element to the document). */
        var hiddenLink = document.createElement('a');

        /* Just for fun, we'll add a CSS attribute of [ style.display = "none" ]. Remember: You can never be too sure! */
        hiddenLink.style.display = "none";

        /* Set the 'href' attribute of the hidden link we just created, to the 'fileNameOrURL' argument received by this function. */
        hiddenLink.setAttribute('href', fileNameOrURL);

        /* Now, let's take advantage of the browser's built-in parser, to remove elements from the original 'fileNameOrURL' argument received by this function, without actually modifying our newly created hidden 'anchor' element.*/ 
        fileNameOrURL = fileNameOrURL.replace(hiddenLink.protocol, ""); /* First, let's strip out the protocol, if there is one. */
        fileNameOrURL = fileNameOrURL.replace(hiddenLink.hostname, ""); /* Now, we'll strip out the host-name (i.e. domain-name) if there is one. */
        fileNameOrURL = fileNameOrURL.replace(":" + hiddenLink.port, ""); /* Now finally, we'll strip out the port number, if there is one (Kinda overkill though ;-)). */  

        /* Now, we're ready to finish processing the 'fileNameOrURL' variable by removing unnecessary parts, to isolate the file name. */

        /* Operations for working with [relative, root-relative, and absolute] URL's ONLY [BEGIN] */ 

        /* Break the possible URL at the [ '?' ] and take first part, to shave of the entire query string ( everything after the '?'), if it exist. */
        fileNameOrURL = fileNameOrURL.split('?')[0];

        /* Sometimes URL's don't have query's, but DO have a fragment [ # ](i.e 'reference anchor'), so we should also do the same for the fragment tag [ # ]. */
        fileNameOrURL = fileNameOrURL.split('#')[0];

        /* Now that we have just the URL 'ALONE', Let's remove everything to the last slash in URL, to isolate the file name. */
        fileNameOrURL = fileNameOrURL.substr(1 + fileNameOrURL.lastIndexOf("/"));

        /* Operations for working with [relative, root-relative, and absolute] URL's ONLY [END] */ 

        /* Now, 'fileNameOrURL' should just be 'fileName' */
        fileName = fileNameOrURL;

        /* Now, we check if we should show UNIX dot-files, or not. This should be either 'true' or 'false'. */  
        if ( showUnixDotFiles == false )
            {
                /* If not ('false'), we should check if the filename starts with a period (indicating it's a UNIX dot-file). */
                if ( fileName.startsWith(".") )
                    {
                        /* If so, we return a blank string to the function caller. Our job here, is done! */
                        return "";
                    };
            };

        /* Now, let's get everything after the period in the filename (i.e. the correct 'file extension'). */
        fileExt = fileName.substr(1 + fileName.lastIndexOf("."));

        /* Now that we've discovered the correct file extension, let's return it to the function caller. */
        return fileExt;
    };

Disfrute! ¡De Nada!:

 1
Author: James Anderson Jr.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-29 02:26:44

Si está tratando con url web, puede usar:

function getExt(filename){
    return filename.split('.').pop().split("?")[0].split("#")[0];
}

getExt("logic.v2.min.js") // js
getExt("http://example.net/site/page.php?id=16548") // php
getExt("http://example.net/site/page.html#welcome") // html

Demo: https://jsfiddle.net/squadjot/q5ard4fj /

 1
Author: Jakob Sternberg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-07 21:38:31
fetchFileExtention(fileName) {
    return fileName.slice((fileName.lastIndexOf(".") - 1 >>> 0) + 2);
}
 1
Author: Ishu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-27 07:21:01
var filetypeArray = (file.type).split("/");
var filetype = filetypeArray[1];

Este es un mejor enfoque omi.

 0
Author: Chathuranga,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-06 15:01:00

En el nodo.js, esto se puede lograr mediante el siguiente código:

var file1 ="50.xsl";
var path = require('path');
console.log(path.parse(file1).name);
 0
Author: Jibesh Patra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-27 09:40:14
var file = "hello.txt";
var ext = (function(file, lio) { 
  return lio === -1 ? undefined : file.substring(lio+1); 
})(file, file.lastIndexOf("."));

// hello.txt -> txt
// hello.dolly.txt -> txt
// hello -> undefined
// .hello -> hello
 0
Author: NSD,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-07 00:24:51

Prefiero usar lodash para la mayoría de las cosas, así que aquí hay una solución:

function getExtensionFromFilename(filename) {
    let extension = '';
    if (filename > '') {
        let parts = _.split(filename, '.');
        if (parts.length >= 2) {
        extension = _.last(parts);
    }
    return extension;
}
 0
Author: omarjebari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-12 23:33:41