将字符串转换成二进制字符串 - 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP