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

Updated on: 30-Sep-2020

184 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements