Caesars Cipher Explaination

Tell us what’s happening:
Can Anyone explain “/[A-Z]/G, L => String.fromCharCode” part of the code given below ?

Your code so far

function rot13(str) { // LBH QVQ VG!
  return str.replace(/[A-Z]/g, L => String.fromCharCode((L.charCodeAt(0) % 26) + 65));
}

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36.

Link to the challenge:
https://www.freecodecamp.org/challenges/caesars-cipher

/[A-Z]/g is a regex pattern, it says match any character that is one of ABCDEFGHIJKLMNOPQRSTUVWXYZ. The g (not G) is a flag that says to the regex do that globally: ie in this case (using with replace) for every character, not just the first one the regex matches.

L is just an arbitrary name for an argument passed to a function L => String.from..... is basically the same as writing function(L) { return String.from.....

replace takes two arguments, the pattern to match on (which is a regex here), and what to replace the match with (in this case a function is used to specify how the matches should be treated) - someString.replace(pattern, replacement)

2 Likes