How to replace leading zero with spaces - JavaScript

We are required to write a JavaScript function that takes in a string that represents a number. Replace the leading zero with spaces in the number. We need to make sure the prior spaces in number are retained.

For example,

If the string value is defined as −

" 004590808"

Then the output should come as −

" 4590808"

Example

Following is the code −

const str = ' 004590808';
const replaceWithSpace = str => {
   let replaced = '';
   const regex = new RegExp(/^\s*0+/);
   replaced = str.replace(regex, el => {
      const { length } = el;
      return ' '.repeat(length);
   });
   return replaced;
};
console.log(replaceWithSpace(str));

Output

This will produce the following output in console −

 4590808

How It Works

The function uses a regular expression /^\s*0+/ to match leading whitespace followed by one or more zeros. The replacement function calculates the length of the matched string and returns the same number of spaces.

Alternative Approach Using String Methods

const replaceLeadingZeros = str => {
   // Find the first non-zero digit position
   let i = 0;
   while (i < str.length && (str[i] === ' ' || str[i] === '0')) {
      if (str[i] === '0') {
         break;
      }
      i++;
   }
   
   // Replace zeros with spaces and keep the rest
   let result = str.substring(0, i);
   while (i < str.length && str[i] === '0') {
      result += ' ';
      i++;
   }
   result += str.substring(i);
   
   return result;
};

console.log(replaceLeadingZeros(' 004590808'));
console.log(replaceLeadingZeros('00123'));
console.log(replaceLeadingZeros(' 00000456'));
 4590808
  123
     456

Conclusion

Both approaches effectively replace leading zeros with spaces while preserving existing whitespace. The regex method is more concise, while the string manipulation approach offers more explicit control over the replacement logic.

Updated on: 2026-03-15T23:18:59+05:30

373 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements