Search code examples
javascriptregexstring-matchingjsbin

Changing Letters Algorithm, works in JSBIN but not in Coderbyte, seeking clarification


I'm going through the CoderByte exercises and I came across the following problem:

>Using the JavaScript language, have the function LetterChanges(str) take the str parameter being passed and modify it using the following algorithm. Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a). Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string.

I wrote out it out in JSBin and it worked fine (even te, but in CoderByte it didn't. I want to ask the community if what I wrote is correct and it's an issue on CoderByte, or if my code is wrong and the issue is with JSBin.

The code is as follows:

function LetterChanges(str) {
    var iLetters = str.split('');
    var newStr = [];

    for (var i = 0; i < str.length; i++) {
        if (/[a-y]/ig.test(iLetters[i])) {
            newStr[i] = String.fromCharCode(iLetters[i].charCodeAt(0) + 1);
            if (/[aeiou]/ig.test(newStr[i])) {
                newStr[i] = newStr[i].toUpperCase();
            }
        } else if (/[z]/ig.test(iLetters[i])) {
            newStr[i] = "A";
        } else if (/[^A-Z]/ig.test(iLetters[i])) {
            newStr[i] = iLetters[i];
        }
    }

    return newStr.join('');
}

Solution

  • Seems like a bug on their back-end JS runner indeed. As you've stated, your code runs fine and should be accepted. Worth reporting it to their support imo.

    Here's an alternative solution specifying a function as second parameter to .replace():

    function LetterChanges(str) {
      return str.replace(/[a-z]/ig, function(c) {
        return c.toUpperCase() === 'Z' ? 'A' : String.fromCharCode(c.charCodeAt(0) + 1);
      }).replace(/[aeiou]/g, function(c) {
        return c.toUpperCase();
      });
    }