'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]
}
}
Solution 1:[1]
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)
Solution 2:[2]
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);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Abhay Prince |
