I am creating a program in javascript which which asks the user to enter a sentence and then encrypt the sentence by replacing each letter with a letter 15 characters down the alphabet. I am unsure on how to have the input keep the special characters and spaces and not try to encrypt those.
let userInput = prompt("Please enter any text to encrypt it:");
let lowerInput = userInput.toLowerCase();
function startEncryption() {
let encryptedMessage = "";
let shift = 15;
for (letter of lowerInput) {
encryptedMessage += shiftLetter(letter, shift);
}
console.log(encryptedMessage);
}
startEncryption();
function shiftLetter(letter, shift) {
let newLetter = "";
let letterCode = letter.charCodeAt(0);
let newLetterCode = letterCode + shift;
if (newLetterCode < 97) {
newLetterCode += 26;
} else if (newLetterCode > 122) {
newLetterCode -= 26;
}
newLetter = String.fromCharCode(newLetterCode);
return newLetter;
}
you could add a guard clause to your shiftLetter function, exit early if an invalid letter/symbol is found.
function shiftLetter(letter, shift) {
if (!letter.match(/^[a-z]$/i)) { return letter }
// the rest of your code
}