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);
}
```

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
}
getPadLength('24') // 4
getPadLength('52367') // 6
getPadLength('102367') // 6
```

Now a function to pad with zeros

```
function padZeros (num) {
const numStrg = num.toString()
const padding = getPadLength(numStrg)
return numStrg.padStart(padding, '0')
}
padZeros(24) // '0024'
padZeros(10235) // '010235'
padZeros(102356) // '102356'
[2, 64, 512, 1024, 32768].map(padZeros)
// ['0002', '0064', '0512', '1024', '032768']
```

thank you for your answer…

```
function padZeros (num, mynumber) {
const numStrg = num.toString() + mynumber;
const padding = getPadLength(numStrg)
return numStrg.padStart(padding, '0')
}
```

console.log(padZeros(‘ABCD0001’, 1)); // 0ABCD00011

expected output: ABCD0002

very nice, but it deprecated as NodeJs saying…

What i gave you just deals with the numbers. I thought you might be able to figure out the rest

Maybe you could split the string first. Then join afterwards.

Sorry, this happens if you switch to often between PHP and JS

Use substring() instead.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.