Can u help me with my code

Tell us what’s happening:

   **Your code so far**

function rot13(str) {
for(let i=0;i<str.length;i++) 
if ("A".charCodeAt(0) < str.charCodeAt(i) &&  str.charCodeAt(i)< "Z".charCodeAt(0))
if("A".charCodeAt(0) < str.charCodeAt(i)-13)



 return str;


rot13("SERR PBQR PNZC");
   **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36.

Challenge: Caesars Cipher

Link to the challenge:

the first thing I see is

this is not checking what you want, you can’t chain comparisons like that in javascript, you need to have two separate comparisons joined with a &&

1 Like

The first thing i see, is a problem with .replace.

The replace method like you called it here replaces every matching Char. So if your programm runs, it changes the “E” in “SERR PBQR PNZC” to “R”, like it should. Then you get the string “FRRR PBQR PNZC”. So now your programm goes on and wants to change the third “R” to an “E”. But the .replace method replaces every “R” in your string with an “E”. So you get “SEEE PBQE PNZC”. So you constantly change your string, including the chars you already converted.
I’m not an expert, but i think you can’t change single chars in a string with the replace method. You need something else here.

Also for further use of the replace method: strings are immutable, str.replace(…) doesn’t change your str variable. You need to assign it to a new variable, like
var newStr = str.replace(…)

To solve this problem, i think you could define an empty string before your for loop. And then add the correct char to this string in every loop.
var newStr = “”

newStr += String.fromCharCode(str.charCodeAt(i)-13)

You will also get a problem with the convertion of “N” to “A”. But i think you will figure that one out.

1 Like

strings in JS are immutable objects and therefore you must assign the end result of replace to a new string, as the replace function does not alter the input string itself.

Replace also doesn’t work based on indices like what you tried to do. It finds the matches in the input string with your 1st argument, then replaces the first with the 2nd argument. Example:

const ex='I like food so so much';
const ex1=str.replace('like', 'hate');
const ex2=str.replace('so' , 'soo');

console.log(ex1) //prints 'I hate food so so much'
console.log(ex2) //prints 'I like food soo so much'

here’s some documentation on String.prototype.replace() on MDN.

1 Like

thank you everyone for your help
have a nice day…Cheers