你可以使用
replace()
并在同一循环内进行所有替换:
function renameFiles(sFolder, sString1, sString2, sString3, sString4) {
var oFSO, oFile, oFolder;
var re, index;
var sName;
var i = 0, n;
oFSO = new ActiveXObject("Scripting.FileSystemObject");
oFolder = oFSO.GetFolder(sFolder);
try {
index = new Enumerator(oFolder.Files);
for (; !index.atEnd(); index.moveNext()) {
oFile = index.item();
sName = oFile.Name;
sName = sName.replace(sString1, sString2);
sName = sName.replace(sString3, sString4);
if (oFile.Name != sName) {
i++;
oFile.Name = sName;
}
}
}
catch(e) {
WScript.Echo("Could not access folder " + sFolder + " because\n" + e.description);
return 0;
} finally {
oFSO = null;
re = null;
return i;
}
}
或者您可以使用一个数组os对,遍历这些对并传递任意数量的对。。。
renameFiles(sFolder, [
[sStringToFind1, sStringToReplace1],
[sStringToFind2, sStringToReplace2],
// ...,
[sStringToFindN, sStringToReplaceN],
]);
function renameFiles(sFolder, arrayOfPairs) {
var oFSO, oFile, oFolder;
var re, index;
var sName;
var i = 0, n;
oFSO = new ActiveXObject("Scripting.FileSystemObject");
oFolder = oFSO.GetFolder(sFolder);
try {
index = new Enumerator(oFolder.Files);
for (; !index.atEnd(); index.moveNext()) {
oFile = index.item();
sName = oFile.Name;
for (var j = 0; j < arrayOfPairs.length; j++) {
sName = sName.replace(arrayOfPairs[j][0], arrayOfPairs[j][1]);
}
if (oFile.Name != sName) {
i++;
oFile.Name = sName;
}
}
}
catch(e) {
WScript.Echo("Could not access folder " + sFolder + " because\n" + e.description);
return 0;
} finally {
oFSO = null;
re = null;
return i;
}
}