將字串轉換成二進位制字串 - JavaScript


我們需要編寫一個 JavaScript 函式,該函式接收一個帶有小寫字母的字串,並返回一個新字串,其中 [a, m] 之間的所有元素均由 0 表示,而 [n, z] 之間的所有元素均由 1 表示。

示例

以下是程式碼示例 −

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));

輸出

以下是在控制檯中的輸出 −

00001 111000 011 010 111

更新時間: 16-9 月-2020

567 瀏覽量

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.