Hello all,
What I'm trying to accomplish is moving a user selected file to a user selected directory - if the selected file already exists in that directory I want to rename that file.
For example: if user selects file 'abc.txt' i want to loop thru the selected directory and check for 'abc.txt'. If it exists copy and rename the file 'abc [1].txt' and if 'abc [1].txt' already exists name it 'abc [2].txt', etc.
The code below works once until I get one duplicated copy 'abc [1].txt' after that it just overwrites that duplicated copy because I don't know how to check for the square brackets([x]).
Code:
function duplicate_file(file,dir) // file = 'abc.txt'
{
// split file name and extension
var name = file.split('.');
// check for dupes in parent directory
var str=name[0];
// ?????????
var patt = new RegExp('\\{'+str+'\\}', 'g');
var dup_array = [];
var d = dir.getDirectoryListing();
var iterator = 1;
for (var l=0;l<d.length;l++)
{
if(d[l].match(patt))
{
dup_array.push(d[l]);
iterator++;
}
}
// put it all back together
var dup = name[0] + ' [' + iterator + '].' + name[1];
return dup;
}
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:)
Bookmarks