PLZ teach me how to use join function to leave signs intact

PLZ teach me how to use join function to leave signs intact
0.0 0

#1

Hi, I’m working and stuck on one of the problems of front-end project. Here’s the explanation of the problem. "One of the simplest and most widely known ciphers is a Caesar cipher, also known as a shift cipher. In a shift cipher the meanings of the letters are shifted by some set amount.

A common modern use is the ROT13 cipher, where the values of the letters are shifted by 13 places. Thus ‘A’ :left_right_arrow: ‘N’, ‘B’ :left_right_arrow: ‘O’ and so on.

Write a function which takes a ROT13 encoded string as input and returns a decoded string.

All letters will be uppercase. Do not transform any non-alphabetic character (i.e. spaces, punctuation), but do pass them on."

I wrote this code and it out puts proper deciphered English words but doesn’t out puts any signs correctly. White spaces are out put as red circles. Please teach me how to leave signs intact.

function rot13(str) { // LBH QVQ VG!
  var words = str.split('');
  for (var i=0;i<words.length;i++){
    if (words[i].match(/[A-Z]/)) {
      words[i] = words[i].charCodeAt();
    } 
    if (words[i]>=78 && words[i]<=91){
      words[i]-=13;
    } else if (words[i]>=65 && words[i]<=78){
      words[i]+=13;
    }
  }
  for (var j=0; j<words.length; j++){
    words[j] = String.fromCharCode(words[j]);
  }
  var result = words.join('');
  return result;
}

#2

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

After the first for loop finishes, your words array has ASCII codes (for the letters A-Z) and all the other elements which are non-letters are their original characters (i.e. spaces, punctuation, etc…).

The problem is your second for loop attempts to convert each element in the words array whether or not it is an ASCII code or not. You only want to use the fromCharCode on the ASCII codes and not the spaces or other punctuation.

My suggestion to salvage most of your existing code is to use the charCodeAt function on all the characters and not just letters A-Z, so that your second for loop will properly convert the ASCII code for the spaces and punctuation back to the original characters.


#3

Thank you! i could solve this problem!