Ceasars Ciper not passing on fcc editor

I have this code snippet which works on my local when I test it.

function rot13(str) {
    const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    let newStr = '';
    str.split(' ').forEach((word) => {        
        for(let i = 0; i < word.length; i++) {
            if (alphabet.includes(word[i])) {
                let pos = alphabet.indexOf(word[i]);
                newStr += alphabet[(pos + 13) % 26];
            } else {
                newStr += word[i];
            }
        }
        newStr += ' '
    });
    return newStr;
}

But apparently doesn’t pass the test on fcc, I am wondering why it’s not passing

I have also tried using methods such as charCodeAt and fromCharCode but still no luck on passing

function rot13(str) {
    const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    let newStr = '';
    str.split(' ').forEach((word) => {        
        for(let i = 0; i < word.length; i++) {
            if (alphabet.includes(word[i])) {
                let ascii = word[i].charCodeAt();
                ascii = ascii + 13
                if (ascii > 90) {
                    ascii = (ascii - 91) + 65
                } 
                
                newStr += String.fromCharCode(ascii);
            } else {
                newStr += word[i];
            }
        }
        newStr += ' '
    });
    return newStr;
}

Every test case I tried works. What’s the test input you’re having problems with?

I’m also unclear what the problem statement is. This code won’t handle lower-case letters, could that be an issue?

there is an issue that makes the returned value differ from the expected one
try with this in your editor (put one of the inputs from the tests in place of the dots):
console.log("->" + rot13(...) + "<-")

This line adds a space to the end of newStr during each iteration of the for loop. Think about what happens in the last iteration of the for loop. This is the problem.

Yes there was an extra space at the end, great catch! Thank you

Did not realize that was the issue, I simply add a trim() at the return statement. Thank you

There was an extra space :slight_smile:

How else could you solve without using the trim method?

hmm probably instead of newStr as a string, should be an empty array where I can put the words, then use join() :man_shrugging: :slight_smile: