Tell us what’s happening:
So I have completed this challenge, my question is any idea how I could avoid hard coding the special chars?
I guess I could use regex but how can I implement it?
thanks.
Your code so far
function rot13(str) {
const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('')
let result = "";
let dictionary = {
'A': 0,
'B': 1,
'C': 2,
'D': 3,
'E': 4,
'F': 5,
'G': 6,
'H': 7,
'I': 8,
'J': 9,
'K': 10,
'L': 11,
'M': 12,
'N': 13,
'O': 14,
'P': 15,
'Q': 16,
'R': 17,
'S': 18,
'T': 19,
'U': 20,
'V': 21,
'W': 22,
'X': 23,
'Y': 24,
'Z': 25,
}
for (let i = 0; i < str.length; i++) {
if (dictionary[str[i]] >= 13) {
let lookUpKey = dictionary[str[i]] - 13;
result += alphabet[lookUpKey];
}
else if (dictionary[str[i]] < 13) {
let lookUpKey = dictionary[str[i]] + 13;
result += alphabet[lookUpKey];
}
else if (str[i] === " ") {
result += " ";
}
else if (str[i] === '?') {
result += '?';
}
else if (str[i] === '!') {
result += '!';
}
else if (str[i] === '.') {
result += '.';
}
}
return result.toUpperCase();
}
rot13("SERR PBQR PNZC");
let regex = /[\s!?.]/g
else if (regex.test(str[i])) {
result += str[i]
}
P.S. I have tried adding the code above to my solution but it didn’t do exactly what I wanted it to do.
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36
Challenge: JavaScript Algorithms and Data Structures Projects - Caesars Cipher
Link to the challenge: