Convert String to 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

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
Updated on: 2020-09-16T10:04:13+05:30

596 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements
close