Simplifying Text Encryption with ROT13 Algorithm in JavaScript

May 21, 2023


In the world of cryptography, the ROT13 algorithm is a simple yet effective method for encrypting and decrypting text. In this article.


  1. discuss the problem.
  2. outline an approach.
  3. present a step-by-step solution and provide code.

Understanding the Problem:

Given a string of text, we want to apply the ROT13 algorithm to encrypt it. The ROT13 algorithm replaces each letter with the letter that is 13 positions later in the alphabet. For example, ‘A’ becomes ‘N’, ‘B’ becomes ‘O’, and so on. The algorithm should preserve the case of the letters and leave non-alphabetic characters unchanged.

My approach for solving this problem:

1- We use the match method with a regular expression /[A-Z]/g to find all uppercase alphabetic characters in the string. These characters will be used for the ROT13 encryption.

2- Next, we split the input string into an array of individual characters using the split method.

3- We apply the map method to each character in the array. For each character, we convert it to its Unicode code using charCodeAt.

4- Inside the map function, we check if the current character is included in the alphabeticCharacter array.
If it is, we determine the new code based on whether the current code is less than 78 (which corresponds to the letter ‘N’ in Unicode).
If the code is less than 78, we add 13 to it; otherwise, we subtract 13 from it.
This effectively rotates the character 13 positions in the alphabet.

5- We convert the modified code back to its corresponding character using String.fromCharCode.

6- Finally, we join all the characters back together into a single string using the join method and return the encrypted string.

My solution:

function rot13(str) {
  let alphabeticCharacter = str.match(/[A-Z]/g);
  str = str
    .map((item) => {
      let code = item.charCodeAt();

      if (alphabeticCharacter.includes(item)) {
        code = code < 78
          ? item.charCodeAt(0) + 13
          : item.charCodeAt(0) - 13;

      return String.fromCharCode(code);

  return str;

rot13("SERR CVMMN!");
Enter fullscreen mode

Exit fullscreen mode

If you have any questions or feedback, please feel free to share them in the comments. Thanks for being here!

About the Author:

Muhammad Awd is a passionate JavaScript developer with expertise in problem-solving and web development. He has a strong track record of delivering high-quality projects and enjoys tackling challenging coding puzzles. You can explore more of Muhammad’s work and connect with him on his LinkedIn and GitHub.

Get in Touch:

If you have any JavaScript development opportunities, project collaborations, or would like to discuss any tech-related topics, feel free to reach out at [email protected]. looks forward to hearing from you and exploring potential collaborations.

Source link

Comments 0

Leave a Reply

Your email address will not be published. Required fields are marked *