简体   繁体   中英

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

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("");
}

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'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM