0

I am a freecodecamp camper. And I need a help to understand how does the below code works which is an advanced solution.

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

// Change the inputs below to test
console.log(rot13("AAA !"));

I do have a little idea on why we are using modulus 26 and then adding 65. but I dont understand what L=> is actually doing. I also understand a bit of regular expression. Please break down this code.

0

1 Answer 1

2

L => declares an arrow function, which is a shorthand syntax for:

function(L) {
    return String.fromCharCode((L.charCodeAt(0) % 26) + 65));
}

When you use a function as the replacement argument in String.prototype.replace(), it gets called on each match of the regular expression, and the return value is used as the replacement.

So the regular expression matches each uppercase letter in str. It calls that function, which calculates the new character code using modulus and addition, converts it back to a character, and that returned character becomes the replacement.

However, the function won't work as written -- it needs to return the result of str.replace().

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

// Change the inputs below to test
console.log(rot13("ABMNTZ !"));

Sign up to request clarification or add additional context in comments.

1 Comment

Looks like there's something missing here: which calculates the new character code by ,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.