How to use Number() Constructor with toString() method In Javascript
In this method, the input string is converted to a number using the Number() constructor, which automatically removes leading zeros. Then, the toString() method converts the number back to a string, resulting in the desired output without leading zeros.
Example: The below code example uses Number() Constructor with toString() method to remove leading zeros in JavaScript.
function removeLeadingZeros(input) {
return Number(input).toString();
}
console.log(removeLeadingZeros("0000123"));
console.log(removeLeadingZeros("000000"));
console.log(removeLeadingZeros("0000100"));
Output
123 0 100
JavaScript Program to Remove Leading Zeros
Leading zeros are zeros that appear at the beginning of a numeric string and do not affect its value but might be undesirable in certain contexts, such as when formatting or comparing numbers.
Below are the approaches to remove leading zeros in JavaScript:
Table of Content
- Using Regular Expression
- Using JavaScript Loops
- Using Number() Constructor with toString() method