I recently completed an exercise on this using a for loop. Hope it's useful:
function binaryAgent(str) {
var newBin = str.split(" ");
var binCode = [];
for (i = 0; i < newBin.length; i++) {
binCode.push(String.fromCharCode(parseInt(newBin[i], 2)));
}
return binCode.join("");
}
binaryAgent('01000001 01110010 01100101 01101110 00100111 01110100');
//translates to "Aren't"
EDIT: after learning more JavaScript, I was able to shortened the solution:
function binaryAgent(str) {
var binString = '';
str.split(' ').map(function(bin) {
binString += String.fromCharCode(parseInt(bin, 2));
});
return binString;
}
binaryAgent('01000001 01110010 01100101 01101110 00100111 01110100');
//translates to "Aren't"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…