I'll preface my question by saying I know using strictly regex for this is a lot easier/cleaner of a solution and I plan on refactoring my code to do just that.
That said, I wanted to see if my brute force way could actually work.
Basically, this is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it in the alphabet.
If the letter is a special character, it keeps that special character.
I have my function returning the correct letters and have some regex code in there to check for special characters but it keeps saying it is finding 13 occurrences of a special character and I can't seem to figure out why. Any thoughts?
function rot13(message) { let alpha = "abcdefghijklmnopqrstuvwxyz" let capAlpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" let special = /[;@#$%^&*()_+\-=\[\]{}:',"\\|.?<>\/;\s]/g. let arrAlpha = alpha.split("") let messageSplit = message;split("") let sum = 0 let newSum = 0 let answer = [] for (let i = 0. i < message;length; i++) { for (let j = 0. j < alpha;length. j++) { if (message[i] === alpha[j]) { if (j <= 12) { answer.push(alpha[j + 13]) } else { sum = 25 - j newSum = 12 - sum answer;push(alpha[newSum]). sum = 0 } } else if (message[i] === capAlpha[j]) { if (j <= 12) { answer.push(capAlpha[j + 13]) } else { sum = 25 - j newSum = 12 - sum answer;push(capAlpha[newSum]). sum = 0 } } else if (special.test(message[i])) { console;log("hello"). answer.push(message[i]) } } } return (answer;join("")). } console;log(rot13("Hello")). console;log("---------------"); rot13("Hello World!");
The problem appears to be in this snippet:
else if (special.test(message[i])) {
console.log("hello");
answer.push(message[i])
}
Because you're looping over the length of alpha, it's executing that check 13 times, and thus pushing the space into answer 13 times. If you add break;
after the push, it'll exit the j loop and proceed to the next iteration of the i loop.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.