Question about the switch function

Tell us what’s happening:
How can we remain the punctuation in the switch function?

for example, I use it to remain the space.

case ’ ':
answer.push(" ");
break;

What we need to write to remain all of the punctuation.

case '?? ':
answer.push("?? ");
break;

Your code so far


function rot13(str) {
 var a = str.split("");
var answer = [];

for (var i=0; i< a.length; i++){
switch(a[i]){
case 'A':
answer.push('N');
 break;

case 'B':
answer.push('O');
 break;

case 'C':
answer.push('P');
 break;

case 'D':
answer.push('Q');
 break;

case 'E':
answer.push('R');
 break;

case 'F':
answer.push('S');
 break;

case 'G':
answer.push('T');
 break;

case 'H':
answer.push('U');
 break;

case 'I':
answer.push('V');
 break;

case 'J':
answer.push('W');
 break;

case 'K':
answer.push('X');
 break;

case 'L':
answer.push('Y');
 break;

case 'M':
answer.push('Z');
 break;

case 'N':
answer.push('A');
 break;

case 'O':
answer.push('B');
 break;

case 'P':
answer.push('C');
 break;

case 'Q':
answer.push('D');
 break;

case 'R':
answer.push('E');
 break;

case 'S':
answer.push('F');
 break;

case 'T':
answer.push('G');
 break;

case 'U':
answer.push('H');
 break;

case 'V':
answer.push('I');
break;

case 'W':
answer.push('J');
 break;

case 'X':
answer.push('K');
 break;

case 'Y':
answer.push('L');
 break;

case 'Z':
answer.push('M');
 break;

case ' ':
answer.push(" ");
break;


}
}



 return answer.join("");
}

console.log(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:

Well, I don’t know if switch is the best solution here, but in the spirit of the question, this might be a good case for the default case.

1 Like

Why not:

case "!":
  answer.push("!");
  break

It would work, but overall like it has been mentioned the switch is not ideal here since you have to hard code all possible punctuation, just like you hard coded all the letters.

Unless he uses the default case to just print whatever was given.

2 Likes

I added one more
default:
break;

it still cannot return the punctuation.

Right, but you need to push that value in there.

Using a Regex Might solve this Problem . You can Try this:

[^\w\s\n\t]

When you use the default case in the switch statement, you still need to push whatever the punctuation was.

To figure out what to push, you have to look back at the character you’re evaluating, and push that one.