Skip to content

Latest commit

 

History

History
39 lines (28 loc) · 1.23 KB

rot13-2.md

File metadata and controls

39 lines (28 loc) · 1.23 KB

ROT13 5 Kyu

LINK TO THE KATA - STRINGS CIPHERS REGULAR EXPRESSIONS ALGORITHMS

Description

How can you tell an extrovert from an introvert at NSA? Va gur ryringbef, gur rkgebireg ybbxf ng gur BGURE thl'f fubrf.

I found this joke on USENET, but the punchline is scrambled. Maybe you can decipher it? According to Wikipedia, ROT13 is frequently used to obfuscate jokes on USENET.

For this task you're only supposed to substitute characters. Not spaces, punctuation, numbers, etc.

Test examples:

"EBG13 rknzcyr." -> "ROT13 example."

"This is my first ROT13 excercise!" -> "Guvf vf zl svefg EBG13 rkprepvfr!"

Solution

const rot13 = str => {
  return str.replace(/[A-Za-z]/g, char => {
    // Calculate the new ASCII code using the code of 'A' or 'a' as the base, depending on the case
    const base = char <= 'Z' ? 'A'.charCodeAt(0) : 'a'.charCodeAt(0)

    // Convert the character to its ROT13 equivalent
    return String.fromCharCode(((char.charCodeAt(0) - base + 13) % 26) + base)
  })
}