- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Replace() with Split() in JavaScript to append 0 if number after comma is a single digit
Let’s say our sample string is −
const a = "250,5";
If the number after “,” is a single digit we have to append a 0 to it,
If the string contains more than one ‘,’, we have to return -1
This can be done simply by combining the split() and replace() functions like this as in the below example −
Example
const a = "250,5"; const roundString = (str) => { if(str.split(",").length > 2){ return -1; } return a.replace(`,${a.split(",")[1]}`, `,${a.split(",")[1]}0`);; } console.log(roundString(a));
Output
The console output for this code will be −
250,50
- Related Articles
- Squaring every digit of a number using split() in JavaScript
- Split String with Comma (,) in Java
- Possible to split a string with separator after every word in JavaScript
- MySQL query to convert a single digit number to two-digit
- Python program to split a string and join with comma
- Get price value from span tag and append it inside a div after multiplying with a number in JavaScript?
- Replace dot with comma on MySQL SELECT?
- How to add comma between every single number in a cell of Excel?
- Split a URL in JavaScript after every forward slash?
- How to split comma and semicolon separated string into a two-dimensional array in JavaScript ?
- Split the sentences by comma and remove surrounding spaces - JavaScript?
- JavaScript Regex to remove text after a comma and the following word?
- Write a program in C++ to replace all the 0’s with 5 in a given number
- Write a program in Python to replace all the 0’s with 5 in a given number
- How to replace multiple spaces with a single space in C#?

Advertisements