- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Replacing zero starting with whitespace in 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. 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
The code for this will be −
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
The output in the console will be −
4590808
Advertisements