Home > Article > Web Front-end > How to convert string to binary in javascript
Conversion method: 1. Use the split() method to convert the string into a character array; 2. Traverse the character array and use the charCodeAt() and toString() methods to convert each character element into a binary value; 3. , use the join() method to splice the array elements and convert them into complete binary values.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Javascript converts a string to binary
Converts a string to a character array
Traverse the character array and use charCodeAt() to convert each character element to ascii code
Use toString(2) to convert the ascii code element to binary
Use join() to splice array elements and convert them into binary strings.
Implementation code:
function strToBinary(str){ var result = []; var list = str.split(""); for(var i=0;i<list.length;i++){ if(i != 0){ result.push(" "); } var item = list[i]; var binaryStr = item.charCodeAt().toString(2); result.push(binaryStr); } return result.join(""); } console.log(strToBinary("我们")); //110001000010001 100111011101100
[Related recommendations: javascript learning tutorial]
The above is the detailed content of How to convert string to binary in javascript. For more information, please follow other related articles on the PHP Chinese website!