How to trim the leading zero in a number in JavaScript
We’ll show you how to trim the leading zero in a number with JavaScript in this brief article. It’s sometimes necessary to remove the leading zero from a string of integers. This task may be accomplished using JavaScript’s built-in features.
- JavaScript Convert 12 Hour AM/PM Time to 24 Hour Time Format
- Get current location in JavaScript using Geolocation API
- 5 Awesome JavaScript String Tips
- How to convert XML to JSON in JavaScript
1. parseInt() function
The parseInt() method parses a string and produces a radix-independent integer.
Let’s take an example.
const numString = "037";
//parseInt with radix=10
const number = parseInt(numString, 10);
console.log(number);
// 37
2. + unary Operator
We’ll use the + unary Operator to transform the operand to a number in the second way.
const numString = "037";
// unary plus operator
const number = +numString;
console.log(number);
// 37
3. Number() construction
Remove the leading zero from an integer using the Number() constructor.
const numString = "037";
// Number constructor
const number = Number(numString);
console.log(number);
// 37
4. Regular expression
To eliminate the zeros from the beginning, we’ll use a regular expression and the replace()
technique in this last procedure.
const numString = "0037";
// regular expression with replace() method
const number = numString.replace(/^0+/, '');
console.log(number);
// 37
The Regular expression searches for zero at the beginning of the text and replaces it with an empty space in the above code.
That’s all I’ve got for today. Thank you for taking the time to read this. Happy Coding..!! 🙂