Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

670
Vistas
Rename a file if already exists in javascript by increment file_1.txt,file_2.txt like that. This code didn't works

I tried this code, It creates a file like file.txt as file_1.txt after that it didn't increased it ,again i gave a filename as file.txt it again shows file_1.txt. I need to increase the value like file_1.txt,file_2.txt,file_3.txt like that.

 while (await client.exists(path+'/'+filename)) {
        var ext = filename.split('.');
        if (i == 0) {
            i = i + 1;
            filename = ext[0] + "_" + i + "." + ext[1]
            i++;
            var newfilename = filename
            // await client.put(buff,path+'/'+newfilename)
            console.log(newfilename)
           
        } else {
            file = ext[0].substr(0, ext[0].lastIndexOf("_" + i));
            i = i + 1;
            filename = filename + "_" + i + "." + ext[1]
        }

    }
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I can't see from the code where you get your index or i from

var newIndex
var newFilename

function addNewFilename(fileName) {
  // find index with regex match number
  let number = fileName.match(/\d+/)

  // if number exist just increase the index
  if (number != null) {
    let currentIndex = number[0]
    newIndex = +currentIndex + 1
    return newFilename = fileName.replace(/\d+/, newIndex);
  }
  // if number is null we add '_1'
  else {
    newIndex = '_1'
    let ext = fileName.split('.')
    return newFilename = ext[0] + newIndex + '.' + ext[1]
  }
}

let file1 = addNewFilename('file.txt')
let file2 = addNewFilename('file_1.txt')
let file3 = addNewFilename('file_31.txt')

console.log('file1:', file1)
console.log('file2:', file2)
console.log('file3:', file3)

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can try this

function getNewFileName(fileName){
  const [name, ext] = fileName.split('.');
  const nameParts = name.split('_');
  let suffixNumber = '';
  if(nameParts.length > 1){
    //name has _n suffix 
    const n = Number(nameParts.pop());
    suffixNumber = n+1;
  
    fileName = nameParts.pop()+'_'+suffixNumber;
  }
  else{
    //name does not have number suffix, so assign it to 1, so that fileName would be file_1.ext
    suffixNumber = 1;
    fileName = nameParts.pop()+'_'+suffixNumber;
  }
  console.log(fileName);
}

// Just to show the output in the console
//  Remove these lines once adding this code to your file
getNewFileName('file.jpg');
getNewFileName('file_1.jpg');
getNewFileName('file_2.jpg');
getNewFileName('file_3.jpg');
//----------

And you can use this as below

while (await client.exists(path+'/'+filename)) {
    filename = getNewFileName(filename);
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda