Can be done by combining your file name extraction method with the methods substr
and lastIndexOf
.
Where:
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.
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.
Where:
A string represented the value to be searched for. If valorBuscado
for an empty string, índice
is returned.
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>
A great answer. I’m glad you used lasIndexof.
– Maury Developer
I would like to know the reason for the down vote. It would be good for the improvement of the answer.
– Augusto Vasques