Cesar's Cipher - Cant get punctuation right

Tell us what’s happening:
Everything else is being decoded, but I cant seem to get the punctation to carry over. Not sure if my regex is setup right or even valid.

Please help. Much appreciated!!


Your code so far

function rot13(str) {
///establish alphabet or rule
let alphArr = alpha.split('')

//split given string into array
let strArr = str.split("")
console.log("original string: " + strArr)
console.log(typeof strArr[4])
let newArr = []

// for each letter in the given string. find its position /index on the alphabet or rule thenr educe that position by 13.

for (let i = 0; i <= strArr.length; i++){

if (strArr[i] === ' ')
{newArr.push(" ")}

else if (strArr[i] === /A-Za-z0-9_/g) {newArr.push(strArr[i])}

else if (typeof strArr[i] === 'string' && alphArr.indexOf(strArr[i]) >= 13) {newArr.push(alphArr[alphArr.indexOf(strArr[i]) - 13])}

else if (typeof strArr[i] === 'string' && alphArr.indexOf (strArr[i]) < 13){newArr.push(alphArr[alphArr.indexOf(strArr[i]) + 13])}



return newArr.join("");

rot13("SERR PBQR PNZC");

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.2 Safari/605.1.15.

Challenge: Caesars Cipher

Link to the challenge:

I dont remember regexp could be used like that, try using str.test(regexp)

the condition you use with regex checks if the left value is strictly equal to regular expression (===) . Like someone before me suggested, you should use the test method

this is always false

there is no index strArr.length, if you use that index to get a value you get undefined

the punctuation returns true for this, as indexOf will return -1

1 Like

For the special characters “!”, “?” and “.” I have added the following instruction to your code and it works:

else if (strArr[i] == "!" | strArr[i] == "." | strArr[i] == "?") {newArr.push(strArr[i]);}

That also will work!

let reg = /[!?.]$/
else if (reg.test(strArr[i]) == true) {newArr.push(strArr[i];
1 Like

Thank you for the feedback!

Hi Moriel!

Thank you for your great help with this. It worked like a charm. Much appreciated!


1 Like

Thank you for your help with this! Much appreciated.

Thank you Sylvant! I got it sorted.