Remove the leading Zeros from a Number in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 07 20211 min read

banner

Photo by Lili Kovac

Remove the leading Zeros from a Number in JavaScript #

To remove the leading zeros from a number, call the parseInt() function, passing it the number and 10 as parameters, e.g. parseInt(num, 10). The parseInt function parses a string argument and returns a number with the leading zeros removed.

index.js
const num = '00123'; const withoutLeading0 = parseInt(num, 10); console.log(withoutLeading0); // ๐Ÿ‘‰๏ธ 123

We passed the following parameters to the parseInt function:

  1. the value to parse
  2. the radix - for our purposes it should be 10, however it does not default to 10, so specify it

The parseInt method returns an integer that is parsed from the given string.

It would work even if we had non digit characters at the end of the string.

index.js
const num = '00123HELLO_WORLD'; const withoutLeading0 = parseInt(num, 10); console.log(withoutLeading0); // ๐Ÿ‘‰๏ธ 123

An alternative solution is to use the unary + operator.

To remove the leading zeros from a number, use the unary plus + operator, e.g. +num. The unary plus operator attempts to convert the num variable to a number if it isn't already, removing all the leading zeros.

index.js
const num = '00123'; const withoutLeading0 = +num; console.log(withoutLeading0); // ๐Ÿ‘‰๏ธ 123

You can think of the unary plus operator as an attempt to convert the value to a number.

If the value can be converted to a number, it will remove all the leading zeros.

However, if it can't be converted into a number, it returns NaN.

index.js
const num = '00123HELLO_WORLD'; // would be NaN if the number contains characters const withoutLeading0 = +num; console.log(withoutLeading0); // ๐Ÿ‘‰๏ธ NaN

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee