How to trim leading zeros from a string number in JS

If you have a string number with leading zero. Example 001, 002, 01, …. How to remove it? In this simple post, I’ll show you how can we do that. Let’s go.

There are a lot of ways to do that:

1
2
3
4
5
6
7
8
9
10
11
12
13
var strNumber = "001";

// 1. using parseInt function
parseInt(strNumber, 10);

// 2. using + operator
+strNumber;

// 3. using Number object
Number(strNumber);

// 4. using regex
strNumber.replace(/^0+/, '');

Note:

  • With parseInt function 10 we call it’s the radix (an integer between 2 and 36 that represents the radix - the base in mathematical numeral systems, of the string). In this case, we need to tranforms from a string number to a real number, so we will pass 10. Read refer link below to more information.
  • ^ in regex that means, find in the string with leading zero.
  • 0+ means, find all zero nearby.

Refer

 Comments
Comment plugin failed to load
Loading comment plugin