ROT13 JavaScript One-Liner Explained

Break down the famous ROT13 JavaScript one-liner step by step. Understand the regex, charCodeAt, String.fromCharCode, and the clever ternary trick for shifting letters.

Programming

Detailed Explanation

The ROT13 JavaScript One-Liner

One of the most elegant ROT13 implementations is this JavaScript one-liner:

const rot13 = s => s.replace(/[a-zA-Z]/g, c =>
  String.fromCharCode(c.charCodeAt(0) + (c.toLowerCase() < 'n' ? 13 : -13))
);

Let's break it down piece by piece.

Step 1: The Regex /[a-zA-Z]/g

This regular expression matches every alphabetic character (both upper and lowercase) in the string. The g flag ensures all matches are processed, not just the first.

Non-alphabetic characters (digits, spaces, punctuation) are not matched and pass through unchanged.

Step 2: The Replace Callback

String.prototype.replace accepts a callback function that receives each matched character. The callback returns the replacement character.

Step 3: charCodeAt(0)

Returns the Unicode code point of the character:

  • A = 65, B = 66, ..., Z = 90
  • a = 97, b = 98, ..., z = 122

Step 4: The Ternary Trick

c.toLowerCase() < 'n' ? 13 : -13

This is the clever part. Instead of using modular arithmetic:

  • If the letter is in the first half (A–M or a–m): add 13 to shift forward
  • If the letter is in the second half (N–Z or n–z): subtract 13 to shift backward

This avoids the need for the modulo operator entirely.

Step 5: String.fromCharCode

Converts the new code point back to a character.

Trace Example

For the string "Hello":

H (72) → 72 + ('h' < 'n' ? 13 : -13) = 72 + 13 = 85 → U
e (101) → 101 + ('e' < 'n' ? 13 : -13) = 101 + 13 = 114 → r
l (108) → 108 + ('l' < 'n' ? 13 : -13) = 108 + 13 = 121 → y
l (108) → 121 → y
o (111) → 111 + ('o' < 'n' ? 13 : -13) = 111 - 13 = 98 → b

Result: "Uryyb"

Alternative: Using Modulo

const rot13 = s => s.replace(/[a-zA-Z]/g, c => {
  const base = c <= 'Z' ? 65 : 97;
  return String.fromCharCode(((c.charCodeAt(0) - base + 13) % 26) + base);
});

This version uses explicit modular arithmetic and is slightly more readable.

Use Case

This one-liner is frequently encountered in JavaScript coding challenges, technical interviews, and code golf competitions. Understanding each part deepens your knowledge of JavaScript string methods, Unicode, regex replace callbacks, and clever algorithmic thinking.

Try It — ROT13 / Caesar Cipher

Open full tool