The task is to, given a string, replace every letter with its position in the alphabet. So “A” should be converted to 1, “B” to 2, and so on. If anything in the text isn’t a letter, ignore it and don’t return it.
So we can see that this method converts “A” to 65, “Z” to 90, “a” to 97, and “z” to 122. If we subtract 64 from 65 we are left with 1, which is the value that “A” corresponds to. Therefore, if we convert all the letters to capital letter, use charCodeAt(), and subtract 64 from all the integers between 64 and 91, we will have achieved our goal of converting all the letters to their respective alphabet position.
Okay. Let’s make this happen! First we need to create the function.
Then all the text should be converted to capital letters.
Now we are ready to use charCodeAt(). The string of uppercase letters will be converted into an array that we can map over, using charCodeAt() for each letter.
At this point, a new array with the correct numerical values can be created. It will be made using the filter() method. For every number in the array that is greater than 64 and less than 91, place into the new array that number.
Afterwards, a third array with the correct numerical values is made by mapping over the previous array and subtracting 64 from each number in the array.
Lastly, we convert the final array back to a string and return the string.
All together, the function in its entirety can be seen below.