我需要您的帮助来修改以下功能。目前,该函数检查字符串中是否存在重复名称。如果找到重复项,它会自动添加 -number 即。123456-2。但是,如果我的字符串已经有一个数字和一个破折号,它只会增加最后一个不应该发生的数字。IE。123456-2012 到 123456-2013,其中字符串应为:123456-2012-2。关于如何纠正它的任何想法?
function test() {
var filename = "123456-2012"
var x = confirm('Duplicate record found!\n\n \''+filename+'\' \n\n rename and add record to the databse as:\n\n \''+new_name(filename)+'\'')
if (x == true) {
alert("adding...")
filename = new_name(filename)
alert(filename)
}
else { return }
}
var exists = 0
function file_exists(name) {
exists = 1 - exists
return exists
}
function new_name(suggested) {
if (!file_exists(suggested)) { return suggested }
var have_index = suggested.match(/^(.+)\-(\d+)$/)
var unused_index
if (have_index && have_index[2]) {
base = have_index[1]
unused_index = ++have_index[2]
} else {
base = suggested
unused_index = 2
}
while (file_exists(base + "-" + unused_index)) { unused_index++ }
return base + "-" + unused_index
}