Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Interchanging a string to a binary string in 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
The code for this will be −
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
The output in the console will be −
00001 111000 011 010 111
Advertisements