-1

Currently in my application I have an increment logic as below, and it fails now when b value above 9 (i.e 00010, 00011). As the limit is 4 digits which should become 0010, 0011 and so on.

How can i make value to 0010 instead of 00010

var b = 0; 
for (var p = 0; p < tabarray.length; p++)
{ 
   b = b + 1; 
   tabarray[p].ItemKey = "000" + b; 
}
xxxmatko
  • 4,017
  • 2
  • 17
  • 24
user3916007
  • 189
  • 1
  • 9

1 Answers1

2

You could use String#slice and take only the last 4 digits.

var b = 0; 

for (var p = 0; p < 10; p++) { 
    b = b + 1; 
    console.log(("000" + b).slice(-4));
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • How can i convert it back to integer from string. I am currently trying with parseint but it reduces the length from 0001 to 1. – user3916007 Dec 02 '16 at 23:02
  • `parseInt` converts a string to a number, and the number has no length. you can use either a string or a number, but not something between. – Nina Scholz Dec 03 '16 at 07:45