Weekly Coding Challenge: Letter Substitution Cipher – written in JavaScript

Posted by

2 min read ~ Hello readers! It’s really important for me to continue my practice and learning. Lately, I have been completing a coding challenge a day with codewars. This helps me keep my skills sharp and see how other devs all over the planet would solve these problems. Being able to see other solutions expands my mind for solving future problems in a clever and efficient way. Today, the problem set focuses on JavaScript.


ROT13 is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it in the alphabet. ROT13 is an example of the Caesar cipher.

Create a function that takes a string and returns the string ciphered with Rot13. If there are numbers or special characters included in the string, they should be returned as they are. Only letters from the latin/english alphabet should be shifted, like in the original Rot13 “implementation”.

JavaScript Solution

function rot13(message){
  let alphabet = 'abcdefghijklmnopqrstuvwxyz';
  let cipher = '';
  message.split('').forEach(str => {
    if (alphabet.indexOf(str) !== -1 || upperAlpha.indexOf(str) !== -1) {
      let finStr = '';
      if (str === str.toUpperCase()) {
        finStr = upperAlpha.substr(upperAlpha.indexOf(str, upperAlpha[-1])) + upperAlpha.substr(0, upperAlpha.indexOf(str))
        cipher += finStr[finStr.indexOf(str) + 13]
      } else {
        finStr = alphabet.substr(alphabet.indexOf(str, alphabet[-1])) + alphabet.substr(0, alphabet.indexOf(str))
        cipher += finStr[finStr.indexOf(str) + 13]
    } else {
       cipher += str;
  return cipher

Disclaimer: *Now, as much as I am tempted to use ES8 & ES9 functions to reduce the number of lines in JavaScript, I am always a fan of readable code that others can understand. Therefore, with the JavaScript examples, I will try to write it without fancy functions as much as possible so it can actually be read and absorbed by my readers. All of my solutions are commented to explain my thinking. Of course, they could always be better. Please feel free to share how you would solve it!*

All solutions are also now on my GitHub profile if you want to check out all of the coding challenges I’ve completed so far!

All credit to problem sets goes to codewars

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s