How to use Loops In Javascript
In this method, the program iterates over the string using JavaScript loop to find the position of the first non-zero digit. It then extracts the substring starting from that position to the end of the string, effectively removing the leading zeros.
Example: The below code example uses JavaScript loop to remove leading zeros in JavaScript.
function removeLeadingZerosIterative(str) {
let i = 0;
while (i < str.length && str[i] === '0') {
i++;
}
// If the entire string consists of zeros, return '0'
if (i === str.length) {
return '0';
}
return str.substring(i);
}
console.log
(removeLeadingZerosIterative("0000123"));
console.log
(removeLeadingZerosIterative("00032"));
console.log
(removeLeadingZerosIterative("00000"));
Output
123 32 0
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
Contact Us