Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
37
rated 0 times [  38] [ 1]  / answers: 1 / hits: 10415  / 11 Years ago, tue, january 14, 2014, 12:00:00

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.


More From » javascript

 Answers
28
function incrementString(str) {
// Find the trailing number or it will match the empty string
var count = str.match(/d*$/);

// Take the substring up until where the integer was matched
// Concatenate it to the matched count incremented by 1
return str.substr(0, count.index) + (++count[0]);
};


If the match is the empty string, incrementing it will first cast the empty string to an integer, resulting the value of 0. Next it preforms the increment, resulting the value of 1.


[#48711] Monday, January 13, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emilee

Total Points: 365
Total Questions: 113
Total Answers: 109

Location: Monaco
Member since Fri, Sep 24, 2021
3 Years ago
;