Rot13, sometimes spelled all uppercase ROT13 and in archaic terms also known as shift-13, is the method of text encryption, or obfuscation, making it less directly readable, whereby every letter is replaced with the letter that is 13 places away in the Latin alphabet.
As there are a total of 26 letters to rotate around, counting forward and backward both end up at the same letter. In binary jargon, the very same function can be used to decode the text, which is a major convenience over other encryption methods. Numbers and other characters are left unaffected, unless a remark about rot5 is made, in which case digits are rotated around their own decimal ‘alphabet’.
The method is often used in newsgroups when publishing movie spoilers, clues about books or games, or material which is potentially offensive to some. Many email and newsgroup applications contain a rot13 function. One of the oldest applications of rot13 on Usenet must have been this post to net.jokes dated 8 October 1982. It is rumoured to be invented by Julius Caesar to pass around his military secrets, but in our days real encryption is another thing.
If the alphabet were a string of pearls, it wouldn't look this good...
The actual rotation function on lines 1 to 3 has been written to cater for both alpha- and numerical characters. It relies on the modulo operator %
which returns the remainder of a division rather than the division itself. Then after setting up the necessary variables in lines 6 to 8, the function rot13
enters a fast while
loop to evaluate each character in the input string from back to front. This is faster than a for
loop would be, and slower than do
, but more readable. During the loop, a character is checked for its code number with the native charCodeAt
function (line 10), and handed to the rotating function if found to be in the range of lowercase or uppercase letters. An array b
is filled with the new characters, which is also faster than accumulating a string. When the loop ends on line 14, the array is joined together with the empty string ''
and passed back.
function rot( t, u, v ) { return String.fromCharCode( ( ( t - u + v ) % ( v * 2 ) ) + u ); } function rot13( s ) { var b = [], c, i = s.length, a = 'a'.charCodeAt(), z = a + 26, A = 'A'.charCodeAt(), Z = A + 26; while(i--) { c = s.charCodeAt( i ); if( c>=a && c<z ) { b[i] = rot( c, a, 13 ); } else if( c>=A && c<Z ) { b[i] = rot( c, A, 13 ); } else { b[i] = s.charAt( i ); } } return b.join( '' ); } function rot5( s ) { var b = [], c, i = s.length, a = '0'.charCodeAt(), z = a + 10; while(i--) { c = s.charCodeAt( i ); if( c>=a && c<z ) { b[i] = rot( c, a, 5 ); } else { b[i] = s.charAt( i ); } } return b.join( '' ); } function rot135( s ) { return rot13( rot5( s ) ); }
It could be written many other ways.