Increment last number in string with leading zeros

Add leading zeros to increment number
Patriek
06 februari 2022:

Was looking for a simple bit of code to increment the last number in a text and found a little snippet on stackoverflow. It worked well but it didn't add back the leading zeros from the number. So I made some adjustments.

function incrementLast(str, addIfNoNumber) {
if (str === null || str === undefined) throw Error('Argument \'str\' should be null or undefined');
const regex = /[0-9]+$/;
if (str.match(regex)) {
return str.replace(regex, (match) => {
number = parseInt(match, 10) + 1;
if (number.toString().length < match.length) {
number = String(number).padStart(match.length, '0');
}
return number;
});
}
return addIfNoNumber ? str + 1 : str;
}
    I like to see who's visiting my website, do you accept?
    Do you want to accept tracking cookies?