Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

แปลงสตริงเป็นไบนารีใน JavaScript


เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงเป็นอินพุตเพียงอย่างเดียว ฟังก์ชันควรสร้างและคืนค่าการแทนที่แบบไบนารีของสตริงอินพุต

ตัวอย่างเช่น

ถ้าสตริงอินพุทคือ

const str = 'Hello World';

ผลลัพธ์ควรเป็น

const output = '1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100';

ตัวอย่างโค้ด

โค้ดสำหรับการทำงานนี้จะเป็นดังนี้

const str = 'Hello World'; 
const textToBinary = (str = '') => { 
  let res = ''; 
  res = str.split('').map(char=> { 
    return char.charCodeAt(0).toString(2); 
  }).join(' '); 
  return res; 
}; 
console.log(textToBinary('Hello World'));

ผลลัพธ์

ผลลัพธ์ในคอนโซลจะเป็นดังนี้

1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100