Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function textToBinary(str='', sep=' ') {
- let result = '';
- result = str.split('').map(char => {
- let bite = char.charCodeAt(0).toString(2);
- while (bite.length < 8) {
- bite = '0'+bite;
- }
- return bite
- }).join(sep);
- return result;
- }
- function groupSplit(str, n=1) {
- return str.match(new RegExp('.{1,'+n+'}', 'g'));
- }
- function toBase64(str, addEq=true) {
- const base64charset = [
- 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
- 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
- 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
- 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
- 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
- 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
- 'w', 'x', 'y', 'z', '0', '1', '2', '3',
- '4', '5', '6', '7', '8', '9', '+', '/'
- ]
- let binary = textToBinary(str, '');
- let chunks = groupSplit(binary, 6);
- let vals = [];
- let result = '';
- let eq = 0;
- chunks.forEach(function(val, index) {
- while (val.length < 6) {
- val += '0';
- eq++;
- }
- vals.push((parseInt(val, 2)));
- });
- vals.forEach(function(val, index) {
- result += base64charset[val];
- });
- if (addEq) {
- for (let i = 0; i < eq/2; i++) {
- result += '=';
- }
- }
- return result;
- }
- console.log(toBase64("Hello, World!")); // SGVsbG8sIFdvcmxkIQ==
Add Comment
Please, Sign In to add comment