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:
- discuss the problem.
- outline an approach.
- 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!
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 muhmmad.awd@gmail.com. looks forward to hearing from you and exploring potential collaborations.
Top comments (4)
Perhaps:
Or maybe:
Yeah, my golfed version works like quite identical 👍
github.com/0x04/string-mutilator/b...
your solution is amazing, wow just one line
any Idea to make it better?