How to write a rot13 function in JavaScript

  1. JavaScript rot13 implementation

In this article, we’ll look at a few different ways to create an implementation of the rot13 (rotate 13 places) cipher in JavaScript.

The ROT13 cipher is a really simple substitution encryption algorithm which shifts the letters in the string provided to 13 places along the alphabet.

The really useful thing about it is you can use the same function to either encrypt and decrypt a string.

For example:

rot13('abcd'); // nopq
rot13('nopq'); // abcd

JavaScript rot13 implementation

There are loads of different ways to implement the rot13 cipher.

A lot of examples start off by having two copies of the alphabet, one starting at ‘A’ and the other at ‘N’.

const input = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const output = 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm';

Then, it’s simply a matter of looping through a string and translating values from the input variable to the output variable.

const rot13 = str => {
    const input = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    const output = 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm';
    let encoded = '';
    for (let i=0; i < str.length; i++) {
        const index = input.indexOf(str[i]);
        encoded += output[index];
    }

    return encoded;
}

This works by finding the position of a character in the input alphabet and picking the character from the same position in the output alphabet.

Instead of using a for loop, a map, reduce, forEach or similar array method could be used by first transforming the string to an array by using the split() function.

Here’s an alternative way the rot13 cipher can be implemented in JavaScript.

const rot13 = str => str.split('')
    .map(char => String.fromCharCode(char.charCodeAt(0) + (char.toLowerCase() < 'n' ? 13 : -13)))
    .join('');

Instead of using pre-defined input / output alphabet variables, we get the char code from each character of the string and then add to it either 13 or -13 depending on whether the character is ‘smaller’ than ‘n’ i.e. before ‘n’ in the alphabet.