How to convert text to binary code in JavaScript?

后端 未结 13 1779
囚心锁ツ
囚心锁ツ 2020-11-28 05:00

Text to Binary Code

I want JavaScript to translate text in a textarea into binary code.

For example, if a user types in "TEST

13条回答
  •  一生所求
    2020-11-28 05:19

    Try this:

    String.prototype.toBinaryString = function(spaces = 0) {
        return this.split("").map(function(character) {
            return character.charCodeAt(0).toString(2);
        }).join(" ".repeat(spaces));
    }
    

    And use it like this:

    "test string".toBinaryString(1); // with spaces
    "test string".toBinaryString(); // without spaces
    "test string".toBinaryString(2); // with 2 spaces
    

提交回复
热议问题