I'm trying to complete the Caesar Cipher Project and why after every word the function adds the letter "M"?
I didn’t want to go easy and use another array of ciphered equivalent letters and simply just loop through them.
I’m aware that my solution is not the best but I wanted to do it in this way. I’m so close to solving it but I don’t understand why after every word the function adds the letter “M”?
Thank you for your time
function rot13(str) {
let ciphered=[];
let myRegex=/\W/g;
let letters=["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"];
let strArr=str.toUpperCase().split("");
for(let i=0; i<strArr.length; i++){
let theIndex=letters.indexOf(strArr[i]);
let newIndex=theIndex+13;
if(theIndex>=13){
newIndex-=letters.length;
ciphered.push(letters[newIndex]);
if(myRegex.test(strArr[i])){
ciphered.push(strArr[i]);
}
}
else{
ciphered.push(letters[newIndex]);
if(myRegex.test(strArr[i])){
ciphered.push(strArr[i]);
}
}
}
let cipheredStr=ciphered.join("");
console.log(cipheredStr);
}
rot13("GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT.");
**Your browser information:**
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1 Safari/605.1.15.
First push: I’m adding 13 to the current letter’s index and checking if it’s over than 26 and I don’t want this to happen. To prevent this from happening I’m subtracting 13 added index from letters.length to find the exact index of the ciphered letter. Then I’m pushing it to the ciphered array.
Second push: For special characters like spaces and question marks etc. I’m checking with regex and pushing them untouched.
Third push: If theIndex is not over 13, I can simply add 13 to it and push the letter to ciphered. Because new index wouldn’t be higher than the letters.length.
Fourth push: Again I’m checking for special characters but I just realized if I remove the first check the program works just the same. But if I remove the last one it doesn’t work. Strange.