- 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
Converting string to a binary string - JavaScript
We are required to write a JavaScript function that takes in a lowercase string and returns a new string in which all the elements between [a, m] are represented by 0 and all the elements between [n, z] are represented by 1.
Example
Following is the code −
const str = 'Hello worlld how are you'; const stringToBinary = (str = '') => { const s = str.toLowerCase(); let res = ''; for(let i = 0; i < s.length; i++){ // for special characters if(s[i].toLowerCase() === s[i].toUpperCase()){ res += s[i]; continue; }; if(s[i] > 'm'){ res += 1; }else{ res += 0; }; }; return res; }; console.log(stringToBinary(str));
Output
Following is the output in the console −
00001 111000 011 010 111
Advertisements