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

Updated on: 19-Oct-2020

95 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements