How to implement the ROT13 algorithm (replace a letter with the 13th letter after it) in JavaScript

1 Answer

0 votes
/*
ROT13 is a simple substitution cipher that replaces a letter with the 13th letter 
after it in the alphabet. Because the English alphabet has 26 letters (13 * 2), 
applying ROT13 twice restores the original text (it is its own inverse).
*/

/**
 * Transforms a string using the ROT13 substitution cipher.
 * 
 * @param {string} text - The input string to transform.
 * @returns {string} The transformed ROT13 string.
 */
function rot13(text) {
    if (typeof text !== 'string') {
        throw new TypeError('Input must be a string');
    }

    // Use regex to match all alphabetic characters and replace them in-place
    return text.replace(/[a-zA-Z]/g, (char) => {
        // Determine the ASCII base code ('A' is 65, 'a' is 97)
        const base = char <= 'Z' ? 65 : 97;
        
        // Shift by 13, wrap around using modulo 26, and convert back to a character
        return String.fromCharCode(((char.charCodeAt(0) - base + 13) % 26) + base);
    });
}

// Input string specified
const message = "Hello, World! 123";

console.log(`Original:  ${message}`);

// Apply ROT13 encryption
const encrypted = rot13(message);
console.log(`ROT13:     ${encrypted}`);

// ROT13 is its own inverse; applying it again decrypts the message
const decrypted = rot13(encrypted);
console.log(`Decrypted: ${decrypted}`);


/*
run:

Original:  Hello, World! 123
ROT13:     Uryyb, Jbeyq! 123
Decrypted: Hello, World! 123

*/

 



answered 2 days ago by avibootz
edited 2 days ago by avibootz

Related questions

...