0

Sorry for the misunderstanding title, I don't know how could explain better.

That's my problem: I have this loop

for(i=1; i<1000; i++){
     "MyName_"+i;
}

This will give the following

MyName_1
MyName_2
...
MyName_10
...
MyName_100

How can I do, in a easy way, to have the same number of digits anytime? This means

MyName_001
...
MyName_010
...
MyName_100

obviously without doing stuff like

if(i<10)
...
if((i>10)&&(i<100))

because the input number is a input so it may be 1000, 10000 or 10000000 and I don't want to write tons of "if()"...

Thank you

  • Lots of duplicates: [`[javascript] zero pad number`](https://stackoverflow.com/search?q=%5Bjavascript%5D+zero+pad+number) – Felix Kling Jul 19 '16 at 08:57

1 Answers1

0

Use JavaScript String#slice method

var input = 100; //input any number
var len = input.toString().length;
for (i = 1; i < input; i++) {
  console.log("MyName_" + ('000000000000000' + i).slice(-len));
}
Vikasdeep Singh
  • 20,983
  • 15
  • 78
  • 104
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • what, no https://github.com/stevemao/left-pad ? :) – Marco Mariani Jul 19 '16 at 08:57
  • What if instead of 100, there will be 1000? – Vikasdeep Singh Jul 19 '16 at 08:58
  • @PranavCBalan, not convinced. Why you are hard-coding '000'? For example, when i will be 100, still you are adding '000'. Actually it should add only '0' – Vikasdeep Singh Jul 19 '16 at 09:02
  • 1
    @VicJordan: The `.slice(-4)` part is important. It returns the last four characters of the string. The last four characters of `"000100"` are `"0100"`. – Felix Kling Jul 19 '16 at 09:04
  • @VicJordan : even `1000` the code will works : `for (i = 1; i < 1000; i++) { console.log( "MyName_" + ('00' + i).slice(-3) ) }` , I just reduced it because the stacksnippet console library not shows that much element... – Pranav C Balan Jul 19 '16 at 09:05