¿Cómo recortar una extensión de archivo de una cadena en JavaScript?


Por ejemplo, suponiendo que x = filename.jpg, quiero obtener filename, donde filename podría ser cualquier nombre de archivo (Supongamos que el nombre del archivo solo contiene [a -A-z0-9 -_] para simplificar.).

Vi x.substring(0, x.indexOf('.jpg'))en Fragmentos de DZone, ¿pero x.substring(0, x.length-4) no funcionaría mejor? Porque, length es una propiedad y no hace la comprobación de caracteres mientras que indexOf() es una función y hace la comprobación de caracteres.

Author: T J, 2010-11-23

22 answers

Si conoce la longitud de la extensión, puede usar x.slice(0, -4) (donde 4 son los tres caracteres de la extensión y el punto).

Si no sabes la longitud @John Hartsock regex sería el enfoque correcto.

Si prefieres no usar expresiones regulares, puedes probar esto (menos performante):

filename.split('.').slice(0, -1).join('.')

Tenga en cuenta que fallará en archivos sin extensión.

 91
Author: Marek Sapota,
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-07-13 14:08:34

No estoy seguro de qué funcionaría más rápido, pero esto sería más confiable cuando se trata de extensiones como .jpeg o .html

x.replace(/\.[^/.]+$/, "")
 347
Author: John Hartsock,
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-21 15:47:14

En el nodo .js, el nombre del archivo sin la extensión se puede obtener de la siguiente manera.

const path = require('path');
var filename = 'hello.html';

path.parse(filename).name; // hello
path.parse(filename).ext;  // .html

Explicación adicional en el nodo .js página de documentación .

 107
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
2018-04-13 14:06:35

x.length-4 solo cuenta con extensiones de 3 caracteres. ¿Qué pasa si tienes filename.jpeg o filename.pl?

EDITAR:

Para responder... claro, si siempre tienes una extensión de .jpg, x.length-4 funcionaría bien.

Sin embargo, si no sabe la longitud de su extensión, cualquiera de una serie de soluciones son mejores/más robustas.

x = x.replace(/\..+$/, '');

O

x = x.substring(0, x.lastIndexOf('.'));

O

x = x.replace(/(.*)\.(.*?)$/, "$1");

O (con el nombre de archivo de suposición solo tiene uno dot)

parts = x.match(/[^\.]+/);
x = parts[0];

O (también con un solo punto)

parts = x.split(".");
x = parts[0];
 102
Author: Jeff B,
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-04-21 20:51:49

Tal vez se puede utilizar la suposición de que el último punto será el delimitador de extensión.

var x = 'filename.jpg';
var f = x.substr(0, x.lastIndexOf('.'));

Si el archivo no tiene extensión, devolverá una cadena vacía. Para arreglar eso use esta función

function removeExtension(filename){
    var lastDotPosition = filename.lastIndexOf(".");
    if (lastDotPosition === -1) return filename;
    else return filename.substr(0, lastDotPosition);
}
 34
Author: Martin Algesten,
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-06-04 11:12:16

En el nodo.versiones de js anteriores a 0.12.x:

path.basename(filename, path.extname(filename))

Por supuesto, esto también funciona en 0.12.x y más tarde.

 13
Author: blah238,
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-12-16 00:01:15

Esto funciona, incluso cuando el delimitador no está presente en la cadena.

String.prototype.beforeLastIndex = function (delimiter) {
    return this.split(delimiter).slice(0,-1).join(delimiter) || this + ""
}

"image".beforeLastIndex(".") // "image"
"image.jpeg".beforeLastIndex(".") // "image"
"image.second.jpeg".beforeLastIndex(".") // "image.second"
"image.second.third.jpeg".beforeLastIndex(".") // "image.second.third"

También se puede usar como un solo revestimiento como este:

var filename = "this.is.a.filename.txt";
console.log(filename.split(".").slice(0,-1).join(".") || filename + "");

EDITAR: Esta es una solución más eficiente:

String.prototype.beforeLastIndex = function (delimiter) {
    return this.substr(0,this.lastIndexOf(delimiter)) || this + ""
}
 10
Author: Andrew Plank,
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-09-29 07:13:37

Otra línea:

x.split(".").slice(0, -1).join(".")
 7
Author: Jacob Bundgaard,
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-01-08 12:10:31

Me gusta este porque es un trazador único que no es demasiado difícil de leer:

filename.substring(0, filename.lastIndexOf('.')) || filename
 7
Author: Jakub,
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-12-23 23:09:49

Aquí hay otra solución basada en expresiones regulares:

filename.replace(/\.[^.$]+$/, '');

Esto solo debería cortar el último segmento.

 6
Author: Chad Johnson,
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-01-29 22:25:52

No se si es una opción válida pero uso esto:

name = filename.split(".");
// trimming with pop()
name.pop();
// getting the name with join()
name.join(''); // empty string since default separator is ', '

No es solo una operación que conozco, pero al menos siempre debería funcionar!

 6
Author: Giacomo Cerquone,
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-29 19:16:42

Simple:

var n = str.lastIndexOf(".");
return n > -1 ? str.substr(0, n) : str;
 5
Author: Dugh,
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-06-21 07:59:11

La respuesta aceptada elimina solo la última parte de extensión (.jpeg), lo que podría ser una buena opción en la mayoría de los casos.

Una vez tuve que eliminar todas las extensiones (.tar.gz) y los nombres de los archivos estaban restringidos a no contener puntos (por lo que 2015-01-01.backup.tar no sería un problema):

var name = "2015-01-01_backup.tar.gz";
name.replace(/(\.[^/.]+)+$/, "");
 4
Author: basic6,
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-02-14 20:06:22
var fileName = "something.extension";
fileName.slice(0, -path.extname(fileName).length) // === "something"
 2
Author: Yas,
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-03-19 07:40:59

Si tiene que procesar una variable que contiene la ruta completa (ej.: thePath = "http://stackoverflow.com/directory/subdirectory/filename.jpg") y desea devolver solo "filename" puede usar:

theName = thePath.split("/").slice(-1).join().split(".").shift();

El resultado será theName = = "filename";

Para probarlo, escriba el siguiente comando en la ventana de la consola de su depurador de Chrome: window.location.pathname.split("/").slice(-1).join().split(".").shift()

Si tiene que procesar solo el nombre del archivo y su extensión (ej.: theNameWithExt = "filename.jpg"):

theName = theNameWithExt.split(".").shift();

El resultado será theName = = "filename", el igual que el anterior;

Notas:

  1. El primero es un poco más lento porque realiza más operaciones; pero funciona en ambos casos, en otras palabras puede extraer el nombre de archivo sin extensión de una cadena dada que contiene una ruta o un nombre de archivo con ex. Mientras que el segundo solo funciona si la variable dada contiene un nombre de archivo con ext como filename.ext, pero es un poco más rápido.
  2. Ambas soluciones funcionan tanto para archivos locales como de servidor;

Pero no puedo no diga nada sobre la comparación de rendimiento con otras respuestas ni sobre la compatibilidad del navegador o el sistema operativo.

Fragmento de trabajo 1: la ruta completa

var thePath = "http://stackoverflow.com/directory/subdirectory/filename.jpg";
theName = thePath.split("/").slice(-1).join().split(".").shift();
alert(theName);
  

Fragmento de trabajo 2: el nombre del archivo con extensión

var theNameWithExt = "filename.jpg";
theName = theNameWithExt.split("/").slice(-1).join().split(".").shift();
alert(theName);
  

Fragmento de trabajo 2: el nombre del archivo con doble extensión

var theNameWithExt = "filename.tar.gz";
theName = theNameWithExt.split("/").slice(-1).join().split(".").shift();
alert(theName);
  
 2
Author: willy wonka,
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-10-12 15:24:27

Aunque es bastante tarde, agregaré otro enfoque para obtener el nombre del archivo sin extensión usando JS -

path.replace(path.substr(path.lastIndexOf('.')), '')

 2
Author: Munim Dibosh,
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-04-05 16:50:08

Aquí es donde las expresiones regulares muy útil! El método .replace() de Javascript tomará una expresión regular, y puede utilizarla para lograr lo que desea:

// assuming var x = filename.jpg or some extension
x = x.replace(/(.*)\.[^.]+$/, "$1");
 0
Author: Alex,
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
2010-11-22 21:32:53

Otro liner - suponemos que nuestro archivo es una imagen jpg >> ej: var yourStr = 'test.jpg";

    yourStr = yourStr.slice(0, -4); // 'test'
 0
Author: SorinN,
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-16 02:47:15

Puedes usar path para maniobrar.

var MYPATH = '/User/HELLO/WORLD/FILENAME.js';
var MYEXT = '.js';
var fileName = path.basename(MYPATH, MYEXT);
var filePath = path.dirname(MYPATH) + '/' + fileName;

Salida

> filePath
'/User/HELLO/WORLD/FILENAME'
> fileName
'FILENAME'
> MYPATH
'/User/HELLO/WORLD/FILENAME.js'
 0
Author: Alan Dong,
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-30 00:28:02
x.slice(0, -(x.split('.').pop().length + 1));
 0
Author: ishandutta2007,
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-25 13:08:50

Este es el código que uso para eliminar la extensión de un nombre de archivo, sin usar regex o indexOf (indexOf no es compatible con IE8). Se asume que la extensión es cualquier texto después de la última'.' caracter.

Funciona para:

  • archivos sin extensión: "myletter"
  • archivos con '.'en el nombre: "mi.carta.txt "
  • longitud desconocida de la extensión de archivo: "my.carta.html"

Aquí está el código:

var filename = "my.letter.txt" // some filename

var substrings = filename.split('.'); // split the string at '.'
if (substrings.length == 1)
{
  return filename; // there was no file extension, file was something like 'myfile'
}
else
{
  var ext = substrings.pop(); // remove the last element
  var name = substrings.join(""); // rejoin the remaining elements without separator
  name = ([name, ext]).join("."); // readd the extension
  return name;
}
 0
Author: Little Brain,
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-27 13:13:40

Usaría algo como x.substring(0, x.lastIndexOf('.')). Si usted va para el rendimiento, no ir para javascript en absoluto :-p No, una declaración más realmente no importa para el 99.99999% de todos los propósitos.

 -1
Author: Lucas Moeskops,
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
2010-11-22 21:29:57