Remove the leading Zeros from a Number in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

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 make sure to specify it
The parseInt function 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.

Use the unary plus + operator to remove the leading zeros from a number, e.g. +num. The unary plus operator attempts to convert the value to a number, which removes all 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, all leading zeros are dropped.

However, if it can't be converted to a number, the operator returns NaN.

index.js
const num = '00123HELLO_WORLD'; // would be NaN if the number contains characters const withoutLeading0 = +num; console.log(withoutLeading0); // 👉️ NaN

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.