# Simplifying Text Encryption with ROT13 Algorithm in JavaScript

May 21, 2023

### Introduction:

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

We’ll:

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
.split("")
.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);
})
.join("");

return str;
}

rot13("SERR CVMMN!");
``````

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