Reputation: 2655
I need your help,
I have the following function below. What is happening, is that when it is executed it changes my native file number (x) to XAI-2012-402518 when all it is supposed to is add a -2 at the end and then increment it every single time after that.
The desired result is: XAI-2012-402517-2
and not XAI-2012-402518
Regularly, without any dashes in the string, it works just fine, but I think the function is confusing the dashes.
Other examples are:
filenumber -> filenumber-2
filenumber2 -> filenumber-3
XAI-2012-402517 -> XAI-2012-402517-2
XAI-2012-402517-2 -> XAI-2012-402517-3
XAI-2012-402517-3 -> XAI-2012-402517-4
ect.
function test2(){
var x = "XAI-2012-402517"
x = x.replace(/^(.+?)(-\d+)?$/, function(a,b,c) { return c ? b+(c-1) : a+'-2'; } );
alert(x)
}
Upvotes: 0
Views: 52
Reputation: 3932
Your function works exactly right. You have an algorithm "capture a digit that comes after the last dash and increase it by one". In "XAI-2012-402517", the digit that comes after the dash is 402517 and therefore it needs to be incremented.
In order to fix this, you need to put a limitation to the condition. For example you may wish to increase only the last digit after dash if it is less than 100:
function test2(x){
x = x.replace(/^(.+?)(-\d{0,2})?$/, function(a,b,c) {
return c ? b+(c-1) : a+'-2'; } );
console.log(x)
}
test2("XAI-2012-402517") //XAI-2012-402517-2
test2("XAI-2012-402517-2") //XAI-2012-402517-3
Upvotes: 1