Can't figure out why my ROT13 converter works with lowercase but it doesn't work with uppercase

193 Views Asked by At

I can't figure out why my ROT13 converter doesn't work with uppercase letters. It works with lowercase letters. I've been trying to find the issue for a while now but with no luck.. Thanks for your help.

Here's the code


var rot13 = str => {

  let alphabet = 'abcdefghijklmnopqrstuvwxyz';
  let alphabetUp = alphabet.toUpperCase();
  let ci = [];

  for (let i = 0; i < str.length; i++) {

    let index = alphabet.indexOf(str[i]);


    // for symbols
    if (!str[i].match(/[a-z]/ig)) {

      ci.push(str[i])
      // for letters A to M
    } else if (str[i].match(/[A-M]/ig)) {
      //lowercase
      if (str[i].match(/[a-m]/g)) {
        ci.push(alphabet[index + 13])
        //uppercase (doensn't work)       
      } else if (str[i].match(/[A-M]/g)) {
        ci.push(alphabetUp[index + 13])
      }
      // for letters N to Z
    } else if (str[i].match(/[n-z]/ig)) {
      //lowercase
      if (str[i].match(/[n-z]/g)) {
        ci.push(alphabet[index - 13])
        //uppercase (doensn't work)       
      } else if (str[i].match(/[N-Z]/g)) {
        ci.push(alphabetUp[index - 13])
      }
    }

  }

  return ci.join("");
}
1

There are 1 best solutions below

1
Dominik Matis On

You can do it easily by adding 13 to index and using modulo 26 to get a new index and then check if the original letter was uppercase or not. Try this

const rot13 = str => {
  let alphabet = 'abcdefghijklmnopqrstuvwxyz';
  
  let newstr = [...str].map(letter => {
    let index = alphabet.indexOf(letter.toLowerCase());
    if(index === -1) {
      return letter;
    }
    index = (index + 13) % 26;
    return letter === letter.toUpperCase() ? alphabet[index].toUpperCase() : alphabet[index];
  })
  
  return newstr.join("");
}

console.log(rot13('hello'))