I can not understand why replace does not work, the task with freecodecamp (given a phrase in which words, letters from the first half of the alphabet need to be replaced with letters of the second half of the alphabet, respectively, ie A = N, B = O, etc.), all solutions associated with this task were through charCodeAt() , is it even possible to solve this problem through replace ?

 function rot13(str) { const alfabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; const half1 = alfabet.split(''); // ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M"] const half2 = half1.splice(0,13); // ["N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] const myStr = str.split(' '); for(let myShifrWords of myStr){ for(let i=0; i<myShifrWords.length;i++){ let e = myShifrWords[i]; function repl(e){ if(half1.indexOf(e)!==-1){ return half1[half2.indexOf(e)]; } else if(half2.indexOf(e)!==-1){ return half2[half1.indexOf(e)] } } return myShifrWords.replace(e, repl); } } } rot13("SERR CVMMN!") 
  • What should be the result? - entithat
  • FREE PIZZA! @Entithat - Kocta
  • Those. can you translate not only with A -> N , but vice versa? - entithat
  • yes, exactly so @entithat - Kocta
  • The problem is: return myShifrWords.replace(e, repl); in the middle of the cycle - Pavel Mayorov

2 answers 2

 function rot13(str) { var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; var map = Object.create(null); for (var q = 0; q < alphabet.length; ++q) { map[alphabet[q]] = alphabet[(q + 13) % alphabet.length]; } return str.replace(/./g, m => map[m] || m); } console.log(rot13("SERR CVMMN!")); 

    And you can still so.

     function replace(str) { return str.replace(/[AZ]/gi, function(letter) { var c = letter.charCodeAt(0); return String.fromCharCode((c - 65 >= 13) ? c - 13 : c + 13); }); } console.log(replace("SERR CVMMN!")); 

    Short description: take a letter from the desired word, look at which part of the alphabet it is (in the first or second), if the first one adds 13 (number of letters in half of the alphabet) using the ASCII code and vice versa, if the letter is from the second part of the alphabet.

    • the code works, but the question is exactly through replace and whether it is possible to do it @entithat - Kocta
    • Can. But I probably won't get very good)) Now I'll try - entithat
    • Az - incorrect - Qwertiy
    • one
      @Qwertiy, stackoverflow.com/questions/4923380/… , understood)) But in any case, it works only with caps. - entithat
    • one
      Yeah, that's right now :) - Qwertiy