Append a number if name is already used?
<p>In Javascript, I have a script that allows me to upload files to my server, then retrieve the output. One component of the output is the name of the file that was uploaded. For example, an output name might look like this:</p>

<pre><code>test.pdf
</code></pre>

<p>The contents of <code>test.pdf</code> are then saved to a <code>localStorage</code> key, with the item name being the name of the file: <code>localStorage.setItem(name, data)</code>.</p>

<p>This works fine, but not when the name of the file is the same as the name of a file that is being uploaded and retrieved.</p>

<p>What I mean by this is that if the user uploads a file with the name <code>Hello 34.pdf</code>, it will save the name of that file and the contents to a LS key. If they upload the same file again, however, or a different file with the same name, then it will replace the current file with the same name.</p>

<p>To remedy this, I need to be able to append a number to the end of the document title, so that  you can have as many versions of the file with the same name in LS.</p>

<p>I know I can check to see if the file has the same name as one already uploaded like this:</p>

<pre><code>var title = $('#file')[0].files[0]["name"];
if (localStorage.getItem(title)) {
  alert("same name");
}
localStorage.setItem(title, data);
</code></pre>

<p>But from there I can't figure out how to add a number to the end. I don't think regex is an appropriate way to do this, as this:</p>

<pre><code>if (title.match(/[\.pdf ]\d/g) != null) {
    var number = title.match(/[\.pdf ]\d/g) + 1;
} else {
    var number = "1";
}
</code></pre>

<p>Is dependent on the <code>.pdf</code> extension to be at the end, and JS regexes are generally bad.</p>

<p>Are there better ways to do this? Should I be indexing the file names a different way? </p>
