Remove the leading zero from a number in JavaScript
In this short article, we’ll explain how to remove the leading zero from a number in JavaScript.
Sometimes we need to delete leading zero from string numbers. JavaScript has built-in options to do this task.
Let's start with examples of different ways.
Different ways to trim leading zero from a number
1. parseInt() function
The parseInt() function parses a string and returns an integer of the specified radix.
Let’s take an example.
const numString = "037";
//parseInt with radix=10
const number = parseInt(numString, 10);
console.log(number);
// 37
2. + unary Operator
In this second method, we’ll use + unary Operator that converts the operand into a number.
const numString = "037";
// unary plus operator
const number = +numString;
console.log(number);
// 37
3. Number() construction
Using the Number() construction, truncate leading zero from a number.
const numString = "037";
// Number constructor
const number = Number(numString);
console.log(number);
// 37
4. Regular expression
In this last method, we will use the regular expression with the `replace()` method to remove the zeros from the beginning.
const numString = "0037";
// regular expression with replace() method
const number = numString.replace(/^0+/, '');
console.log(number);
// 37
In the above code, Regular expression searches zero at the beginning of the string and replace it with an empty space.
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂