
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 Articles
- 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?
- How to Replace null with “-” JavaScript
- How to add leading zero to fixed number length in Excel?
- C# program to replace all spaces in a string with ‘%20’
- 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?
- Golang program to replace the spaces of string with a specific character
- How to replace missing values recorded with blank spaces in R with NA or any other value?
- Trim a string in Java to remove leading and trailing spaces
- How to replace line breaks with using JavaScript?
- HTML5 Input type=number removes leading zero

Advertisements