- 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 digits to form binary using JavaScript
Problem
We are required to write a JavaScript function that takes in a string of digits. Our function should replace any digit below 5 with '0' and any digit 5 and above with '1' and return the resulting string.
Example
Following is the code −
const str = '262355677834342'; const convert = (str = '') => { let res = ''; for(let i = 0; i < str.length; i++){ const el = +str[i]; if(el < 5){ res += 0; }else{ res += 1; }; }; return res; }; console.log(convert(str));
Output
010011111100000
Advertisements