How to extract only the filename without extension using javascript?

Asked

Viewed 536 times

3

I just need to get the name of the file without the extension

// Aqui está obtendo o nome do arquivo com a extensão. Ex: foto.jpg
//Eu só preciso pegar: "foto"

var filename = $('.upload-image-file').val().split('\\').pop(); 

$('.upload_image').addClass('no-flex');
$('#title').val(filename);

2 answers

4


Can be done by combining your file name extraction method with the methods substr and lastIndexOf.


String.prototype.substr(*inicio*[, *quantidade*])

Where:

  • beginning

This is the place to start extracting characters. If a negative number is passed, it is treated as strLength - start, where strLength is the string size.

  • amount

The number of characters to be extracted. If this argument is undefined, all characters of start at the end of the string will be extracted.

Return value

A new string containing the section extracted from the given string. If the length for 0 or a negative number, an empty string is returned.


String.prototype.lastIndexOf(*valorBuscado*[, *índice*])

Where:

  • valued

A string represented the value to be searched for. If valorBuscado for an empty string, índice is returned.

  • index

The index on which the search will start backwards. Any integer is valid.


In this example I made a modification to allow the reader to use the file system itself as a test. I used a <input type="file"> to open a dialog where one or more files can be selected, then for each file applies the logic of fetching all characters from the file name with extension to the last point (lastIndexOf('.')). If the file name has no extension only returns its own name.

function processarArquivo(arquivo){
    // Poderia ser arquivo.mozFullPath.val().split('\\').pop();
    // ou arquivo.webkitFullPath.val().split('\\').pop();
    // mas isso apresenta dois problemas:
    // 1- Só funcionaria No Chrome, Safari e Mozilla. No Opera, Ie e Edge ficariam de fora.
    // 2- Só funcionaria em Windows. Em Linux e MacOsX ficariam de fora.
    // Optei pela solução mais portável que é arquivo.name
    var nomeExt = arquivo.name; 
    
    //Busca todos os caracteres até última ocorrência do ponto(.) se não existir o ponto(.) retorna a própria string.
    var nome = nomeExt.substr(0, nomeExt.lastIndexOf('.')) || nomeExt;
    console.log(nome);
    
}

//Essa função apenas repassa os elementos da fila de arquivos selecionados para o processamento individual
function processarArquivos(e) {
   var arquivos= e.files; 
   for (var i = 0; i < arquivos.length; i++) {
        processarArquivo(arquivos[i]);
   }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <input type="file" multiple onchange="processarArquivos(this)">      
<div>

  • 1

    A great answer. I’m glad you used lasIndexof.

  • 1

    I would like to know the reason for the down vote. It would be good for the improvement of the answer.

-2

Good morning friend !

very simple !

$('.upload-image-file').val().split('\\').pop().split('.').shift()

hug !!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.