In this blog, we will see how to remove a leading zero from a number using JavaScript. There are some built-in ways in JavaScript to do this. The different methods to trim the leading zero are as follows:
- parseInt() function
- A unary operator
- A regular expression
Let’s see each of them one by one.
Table of Contents
parseInt() function
Code
const number = 069
parseInt(number, 10) // 69
the parseInt() function parses a string argument and an integer is returned with the specified radix (number of unique digits).
The parseInt function will accept the number to be trimmed and the radix value as the parameter. The radix value can be an integer value between 2 and 36 which is the base used by the parseInt() function.
Let’s move to second method.
Unary operator
These operators are operations that are performed with just one operand and they come before or after the operator. Plus (+) operator can be used to convert a given string into a number. Let’s look at the below example code. This operator will remove any leading zeros, while converting anything into a number.
Code
const number = 069
+number //69
Regular Expression
Regex is something which can come handy in a lot of ways so in this method we will remove the leading zeros with the regular expression. We have also used regular expression (aka Regex) extensively in our previous blogs. We hope that you know how regex works.
Code
const number = 058
number.replace(/^0+/, "")
Conclusion
After going through this article, we hope that you now know how to use JavaScript to remove leading zeros from a number using three different methods.