字符串中的短划线

时间:2012-09-06 18:00:21

标签: javascript

我需要你的帮助来修改下面的功能。目前,该函数检查字符串中是否存在重复的名称。如果找到重复,它会自动添加-number即。 123456-2。但是,如果我的字符串已经有一个数字和一个破折号,它只会增加不应该发生的最后一个数字。即。 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

} 

1 个答案:

答案 0 :(得分:1)

在new_name函数中执行以下更改

请注意,我在if条件中添加了!have_index[2]

if (have_index && !have_index[2]) { 
      base = have_index[1] 
      unused_index = ++have_index[2] 
   } else { 
      base = suggested 
      unused_index = 2 
   }