I am working on a variation of Caesar's Cipher in JavaScript. The variation is that a random letter is generated and inserted every 2 spaces. I have the encryption working just fine. I have the decryption mostly working. My program decrypts it, but I do not know how to remove the random letters. I am writing a function to remove the letters, my current code for that is as follows:
let decryptedMessage = seoekx tbhea mtidrniughkt
function finalMessage (decryptedMessage) {
let finalMessage = "";
for (let i = 1; i < decryptedMessage.length - 1; i++) {
if (i % 2 === 0) {
finalMessage += decryptedMessage.replace(decryptedMessage[i],"");
}
else {
finalMessage += decryptedMessage[i];
}
}
return finalMessage;
}
const finalMessageResult = finalMessage(decryptedMessageResult);
console.log(`The final decrypted message is ${finalMessageResult}`);
This is my Output:
eseekx tbhea mtidrniughkteseoex tbhea mtidrniughktxseoekxtbhea mtidrniughkttseoekx thea mtidrniughkthsoekx tbhea mtidrniughktaseoekxtbhea mtidrniughktmseoekx bhea mtidrniughktiseoekx tbhea mtirniughktrseoekx tbhea mtidriughktiseoekx tbhea mtidrnighktgseoekx tbea mtidrniughktk
I am thinking I need to pull the finalMessage out of the for loop, but I don't know how to do that because I feel the if statement needs to be in the for loop to loop through the message.
Any help would be appreciated.
I feel I need to have it in a for loop with an if else statement. The logic in my head is to use i % 2 === 0, then to replace that element with "". But clearly what I have in my head and what is being executed are not the same. I am expecting to have the code remove the random letters from the string, creating a readable message.
Looks like your iterator math was just a little off, and it looks like you were overthinking the algorithm! Try this:
let decryptedMessage = "seoekx tbhea mtidrniughkt";
function finalMessage (decryptedMessage) {
let finalMessage = "";
for (let i = 0; i < decryptedMessage.length; i++) {
if ((i + 1) % 3 !== 0) {
finalMessage += decryptedMessage[i];
}
}
return finalMessage;
}
const finalMessageResult = finalMessage(decryptedMessage);
console.log(`The final decrypted message is ${finalMessageResult}`);
A few things I changed:
i + 1
Output: The final decrypted message is seek the midnight