rnd me just racking my brains over your solution
Two things that stood out was that I forgot to escape the . and \d+ is a bit more flexible.
Had to look up slice(1,-1) as well i.e. 'defgh' becomes 'efg' or '[123]' becomes '123'.
One quick question though. Is there any reason not to use this instead and miss out var n. Comes up with the same result in this test.
while(dc.indexOf(file)!=-1){
file=file.replace(/(?:\[(\d+)\])?\.(\w+)$/g,function(j,a,b){
return "["+( a!="" ? parseInt(a)+1 : "0") +"]."+b;
})
}
Cheers
edit: a breakdown of rnd me's code
var dir = ['abc.txt', 'abc[0].txt', 'abc[1].txt', 'xyz.txt', 'somethingElse[23].jpg'],
file ='abc.txt',
n = null;
// *abc.txt*abc[0].txt*abc[1].txt* etc....
var dc = "*"+dir.join("*")+"*";
// while file matches somewhere in dc
// note: file is ammended each iteration.
// eg 1. abc.txt 2. abc[0].txt 3. abc[1].txt
while( dc.indexOf(file)!=-1 ){
file = file.replace(/(\[\d+\])?\.(\w+)$/g, function(j,a,b){
// j is the overall match e.g. '.txt' then '[0].txt' etc .....
// a = the match/capture in the first set of brackets (\[\d+\])? e.g '[0]' or '[1]' or optionally nothing ""
// b = the match/capture in the second set of brackets (\w+) e.g. 'txt' or 'jpg'
// slice (1,-1). Slice out string between the second and second to last character
// e.g. 'abcdefg' becomes 'bcdef' or '[0]' becomes '0' or '[1]' becomes '1'
n = a.slice(1,-1);
// replace j matched portion with '[n].b'
// if n doesn't equal an empty string add 1 to the index
// else set the index to 0
return "["+( (n!="")
? parseInt(n)+1
: "0"
) +"]."+b;
})
}
alert (dir[(dir.push(file))-1]); // abc[2].txt. push returns the length. that's a new one for me:)