I’m creating functionality to increase the last number in a filename with 1.
Samples:
filename01.jpg => filename02.jpg
file01name01.jpg => file01name02.jpg
file01na01me.jpg => file01na02me.jpg
I’m struggling with the cases where the original file name contains the same number two or more times. I only want to increase the last number in the filename.
I have done some research, but not been able to find a correct regex. Perhaps someone could help me.
Ideally I want my code to look something like this:
var filename = "somefilename";
var newFilename = filename.replace(regex,lastNumber + 1);
I’m not sure if it could be done this easy. But I need to figure out the regex before I move on.
Thanks to pivmvb, here is my final solution:
function getIncreasedFileName(fileName){
var newFileName = fileName.replace(/(\D+)(\d+)(\D+)$/,
function(str, m1, m2, m3) {
var newstr = (+m2 + 1) + "";
return m1 + new Array(m2.length+1 - newstr.length).join("0") + newstr + m3;
})
return newFileName;
}
Where:
Then replace the matched string by a function that returns a new string, after doing the following: