# Pattern with auto increment in javascript

I am trying to create the pattern where the number will auto-increment with at least one prefix with zero when the number is over. for example initial value will be `ABCD0001` when I add 1 it will be `ABCD0002` so on it will continuously work like `ABCD9999`. now the digit is over then it will convert to `ABCD010000` means if the digit will over auto the number zero add as like here we can see `ABCD010000` I am trying to create this function but it removes all the zeroes from the code. please help how I create this function which would give the expected output in the javascript. I am trying to create but it not working as below.

It is a little bit inconsistent that you have ABCD0001, ABCD0002 and then go to ABCD10000, ABCD10001. So if you increase the number of digits, you should start with ABCD1, ABCD2 etc.

But here is a solution:

``````let id = "ABCD9991";

for(let i = 0; i < 100; i++)
{
let strings = id.replace(/[0-9]/g, '');
let digits = (parseInt(id.replace(/[^0-9]/g, '')) + 1).toString();
if(digits.length < 4)
digits = ("000"+digits)	.substr(-4);
id = strings + digits;
console.log(id);
}

``````
1 Like

Welcome to the forum @wawane7256 My attempt

First a function to get the required padding length of a given string

``````// strings have a length property '22'.length === 2
function getPadLength ({ length }) {
if (length < 5) return 4
// if an odd number in length return the length + 1
return (length % 2 === 0) ? length : length + 1
}

``````

Now a function to pad with zeros

``````function padZeros (num) {
const numStrg = num.toString()

}

// ['0002', '0064', '0512', '1024', '032768']
``````

``````function padZeros (num, mynumber) {
const numStrg = num.toString() + mynumber;
}
``````

What i gave you just deals with the numbers. I thought you might be able to figure out the rest Sorry, this happens if you switch to often between PHP and JS 