A Dash in a string
<p>I need your help in modifying the following function below. Currently the function checks to see if there is a duplicate name in a string. If there is a duplicate found, it automatically adds -number ie. 123456-2. However, if my string already has a number and a dash it just increments the last number which is not supposed to happen. ie. 123456-2012 to 123456-2013 where the string should read: 123456-2012-2. Any idea as to how to correct it?</p>

<pre><code>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 &amp;&amp; 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

} 
</code></pre>
