I am trying to create the pattern where the number will auto increment with at least one prefix with zero when the number is finished. for example the initial value will be `ABCD0001` when i add 1 it will be `ABCD0002` so on, it will work continuously like `ABCD9999`. now the figure is finished, it will be converted to `ABCD010000` means if the number exceeds the number zero automatically add like here we can see `ABCD010000` I am trying to create this function but it strips all zeros from the code. please help me to create this function which would give expected output in javascript. I try to create but it doesn’t work as below.

It’s a bit inconsistent that you have ABCD0001, ABCD0002, then jump 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 fill with zeros

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

}

[2, 64, 512, 1024, 32768].map(padZeros)

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

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

console.log(padZeros(‘ABCD0001’, 1)); // 0ABCD00011
expected output: ABCD0002

very nice, but it’s deprecated as NodeJs says…

What I gave you is just the numbers. I thought maybe you could figure out the rest Maybe you could split the string first. Then join next.

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