Let's say I have the following string:
aRandomString
I'm then checking my database to see if that string has been used before (or if there's any string that starts with the given one). If it has, I'd like to increment it. The result would be the following:
aRandomString1
If that string exists, it would become aRandomString2
, and so on. I'm assuming I need to complete the following steps: 1. Check for trailing numbers or set to 0, 2. Increment those trailing numbers by 1, append that number to the original string. Just trying to figure out a solid way to accomplish this!
Update
This is what I have so far:
var incrementString = function( str ){
var regexp = /d+$/g;
if( str.match(regexp) )
{
var trailingNumbers = str.match( regexp )[0];
var number = parseInt(trailingNumbers);
number += 1;
// Replace the trailing numbers and put back incremented
str = str.replace(/d+$/g , '');
str += number;
}else{
str += 1;
}
return str;
}
I feel like this should be easier though.