

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Questions & Answers
- How can I replace newlines with spaces in JavaScript?
- Capitalize a word and replace spaces with underscore - JavaScript?
- How to replace multiple spaces with a single space in C#?
- How to preserve leading 0 with JavaScript numbers?
- HTML5 Input type=number removes leading zero
- How to pad a number with leading zeros in JavaScript?
- How to remove white spaces (leading and trailing) from string value in MongoDB?
- How to replace zero with previous value in an R data frame column?
- Trim a string in Java to remove leading and trailing spaces
- How to replace zero with first non-zero occurring at the next position in an R data frame column?
- Replacing spaces with underscores in JavaScript?
- Trim (Remove leading and trailing spaces) a string in C#
- How to Replace null with “-” JavaScript
- How to replace missing values recorded with blank spaces in R with NA or any other value?
- How to add a leading zero to some values in a column in MySQL?
Advertisements