Open In App

JavaScript Program to Remove Leading Zeros

Last Updated : 18 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

1. Using Regular Expression

This approach employs a regular expression to match and remove leading zeros from the input string. The regex pattern ^0+ matches one or more zeros at the beginning of the string. The replace() function replaces the matched pattern with an empty string, effectively removing the leading zeros.

Syntax:

stringName.replace(/^0+/, ");

Example: The below code example uses the regular expression to remove leading zeros in JavaScript.

Javascript
function removeLeadingZerosRegex(str) {
    return str.replace(/^0+(?=\d)/, '');
}

console.log
    (removeLeadingZerosRegex("0000123"));
console.log
    (removeLeadingZerosRegex("000000"));
console.log
    (removeLeadingZerosRegex("0000100"));

Output
123
0
100

2 Using JavaScript Loops

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.

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

3. Using Number() Constructor with toString() method

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.

JavaScript
function removeLeadingZeros(input) {
    return Number(input).toString();
}
console.log(removeLeadingZeros("0000123"));
console.log(removeLeadingZeros("000000")); 
console.log(removeLeadingZeros("0000100"));

Output
123
0
100


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads