0

I'm extracting number from a string and passing it to a function. I want to add 1 to it and then return the string while retaining the leading zeros. I was able to do it using a while loop but not a for loop. The for loop simply skips the zeros.

var addMoreZeros = (numStr)=> {
    let newNumStr = (parseInt(numStr)+1).toString();
    let zerosToAdd = numStr.length - newNumStr.length;
    let zeroPadStr = "";
    let i = 0;
    while (i < zerosToAdd) {
        zeroPadStr += "0";
        i++;
    }
   //This doesn't work
   //for(let i = 0; i++; i < zerosToAdd) {
   //   zeroPadStr+="0";
   //}
    return zeroPadStr + newNumStr;
}
l0h1t
  • 363
  • 2
  • 10

2 Answers2

1

You have your for loop syntax wrong, it should be:

(initializer; condition; increments / decrements)

so:

for(let i = 0; i < zerosToAdd; i++) {}

var addMoreZeros = (numStr)=> {
    let newNumStr = (parseInt(numStr)+1).toString();
    let zerosToAdd = numStr.length - newNumStr.length;
    let zeroPadStr = "";
    for(let i = 0; i < zerosToAdd; i++) {
      zeroPadStr+="0";
    }
    return zeroPadStr + newNumStr;
}
console.log(addMoreZeros("00125"))
dotconnor
  • 1,736
  • 11
  • 22
  • Fun fact: In the third part of loop syntax you can insert any code (not onyl incrementation or decrementation). So this code could look like this: `for(let i = 0; i < zerosToAdd; i++, zeroPadStr+="0") {}` But please don;t do this, it's unreadable ;) – Konrad Nov 19 '18 at 23:44
0

Alternative approach (instead of using for/while):

var addMoreZeros = (numStr, numLength = numStr.length) => `${++numStr}`.padStart(numLength,'0');

// example of usage
console.log(addMoreZeros("124", 5));

Explanation ++numStr coerces the numeric string to a number and increments it, then `${...}` casts the number back to a string. Finally padStart() adds leading zeros.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
  • 1
    `(numStr, numLength = numStr.length) => ...` is probably closer to what OP wants. Also this isn't code golf, no need to use cryptic expressions like `((+numStr+1)+'')`. I think `\`${parseInt(numStr) + 1}\`` is a bit more readable there. I didn't downvote, just giving feedback. – Patrick Roberts Nov 19 '18 at 18:08
  • Thanks. We can also use ++numstr here. – l0h1t Nov 19 '18 at 18:09