Caesar Cipher Solution In JavaScript

Keith Williams
3 min readMay 28, 2021

Caesar Cipher is a type of encryption where you take letters in the alphabet and shift them a certain number of positions. If we have a string “abc” and we wanted to encrypt it by shifting each letter 5 positions, the new string would be “fgh.” For example, five positions from “a” is “f” (1 shift = “b”, 2 shifts = “c”, 3 shifts = “d”, 4 shifts = “e”, 5 shifts = “f”). When we get to the end of the alphabet we wrap around back to the beginning. For example, if we wanted to move “z” up 2 positions it would become “b.”

In the Caesar Cipher problem we are given a string and a number of positions to shift. Our task is to shift each letter in the string that number of positions. In this example we will assume that all the input strings only include lowercase letters. This allows us to use ASCII character codes.

ASCII character codes assign numeric values to letters and symbols. The ASCII codes for the lowercase letters of alphabet are 97–122 (“a” is 97, “z” is 122) as shown in the table above. JavaScript offers built in methods that will return the ASCII code for a given character.

For our solution we first want to create an empty array. This is where we will add our shifted characters later on. Next we want to use a for loop to iterate through each character of the input string. Inside of the for loop we are going to create a variable that we will assign the ASCII code for the new shifted letter.

For each character of the of original string we are identifying the current ASCII code by using the charCodeAt method. We call the method on the input string and pass in the index of the character as an argument. We then want to add the number of position shifts to this number.

We now want to account for numbers larger than 122 where we have to wrap around to the beginning of the alphabet. We are also going to account for inputs with a large number of position shifts. This can be done by using a while loop. If the number assigned to the “code” variable is larger than 122 we want to subtract 122 and then add 96, which will circle though alphabet and bring us to the correct ASCII code.

Now we want to convert that ASCII code back to a letter. To do this we use the fromCharCode method. We create a new string and pass in the ASCII code as an argument.

We then push the new string into our created results array. After we iterate through the entire input string, we now have an array with the newly shifted letters. This can be converted back to a string using JavaScript’s join method.

Here is the final solution.

--

--