0

I have a string that only contains numbers, but the string can not start with a zero.

The first thing I cam up with was this:

let myNumber = "0052";
myNumber = myNumber.split('');
for (let i = 0; i < myNumber.length; i++) {
    if (myNumber[i] == '0') {
        myNumber.splice(i, 1);
        i--;
    } else {
        break;
    }
}
console.log(myNumber);
console.log('result:', myNumber.join(''));

Everything works fine like that.

I thought there might be an other way without using a classical for-loop. My attempt with a for-of loop failed. As soon as I remove the first entry of my array, the index of the loop does not reset, so it skips the second zero in my array. Here is the code for that:

let myNumber = "0052";
myNumber = myNumber.split('');
for (let n of myNumber) {
    if (n == '0') {
        myNumber.shift();
    } else {
        break;
    }
}
console.log(myNumber);
console.log('result:', myNumber.join(''));

What other solutions to this problem are there? Is there a more performant solution?

JiiB
  • 1,432
  • 1
  • 12
  • 26
  • So your spurce code works but you want to explore other methods/solutions? If so then your question is in the wrong place. – NewToJS Feb 16 '18 at 21:11

4 Answers4

5

Regexp: /^[0]+/

let myNumber = "0000000520";
console.log(myNumber.replace(/^[0]+/, ''))
Ele
  • 33,468
  • 7
  • 37
  • 75
5

What you're probably looking for is parseInt function.

const result = parseInt("0052", 10).toString();
console.log(result);

I also added toString() to convert number to a string. parseInt also accepts second argument - the radix. Read more about parseInt

Tomasz Bubała
  • 2,093
  • 1
  • 11
  • 18
1

Use parseInt('0052') = 52

or

parseFloat('0052.29') = 52.29 if your number is float type:

Martin
  • 201
  • 1
  • 4
0

I just have different and simpler approach than yours :)

while(myNumber.length){
  if(myNumber.charAt(0) == '0')
    myNumber = myNumber.substring(1, myNumber.length);
}

DEMO : https://jsbin.com/falejuruwu/1/edit?js,console

Ankush Malik
  • 150
  • 2
  • 11