Hey everyone,
I'm running into some issues with this specific function.
const incrementString = str => {
if (!str.match(/[\d+]$/)){
return str += 1
} else{
return str.replace(/[\d+]$/, match => new Number(match) + 1)
}
}
The goal of this function is to increment the number at the end of a string by 1, and if there isn't one, append a 1 at the end.
string expected
"foobar000" "foobar001"
"foo" "foo1"
"foobar025" "foobar026"
I'm wondering if it's possible to achieve this using regex and replace. I have other solutions in mind involving loops, .length, split, etc., but I'd like to stick to regex if achievable.
Issue: How can I efficiently target the number at the end of the string, including leading zeros, and add 1 to it? Here are some examples where my function is not behaving as expected:
Expected: 'foobar011', instead received: 'foobar11'
Test Passed: Value == 'foo1'
Expected: 'foobar002', instead received: 'foobar2'
Test Passed: Value == 'foobar100'
Test Passed: Value == 'foobar100'
Test Passed: Value == '1'
Thank you all and happy holidays!