Home > Back-end >  Convert Cases in a String
Convert Cases in a String

Time:09-22

I am trying to create a function to reverse all cases in a string. All lower-case letters should be upper-case, and vice versa. For example: reverseCase("Happy Birthday") ➞ "hAPPY bIRTHDAY"

My code below doesn't work. :(

const functionX = X =>
  X === X.toLowerCase() ? X.toUpperCase() : X.toLowerCase();

function reverseCase(string) {
  const letters = string.split('');
  letters.forEach(functionX);
  return letters.join('');
}

console.log(reverseCase('Happy Birthday!'));

CodePudding user response:

The forEach function does not return the output letter even though it executes the functionX for each input letter. You need to use map instead to return the letters.

Try like this:

const functionX = X =>
  X === X.toLowerCase() ? X.toUpperCase() : X.toLowerCase();

function reverseCase(string) {
  const letters = string.split('');
  return letters.map(functionX).join('');
}

console.log(reverseCase('Happy Birthday!'));

CodePudding user response:

Hope its clear

function reverseCase(string) {
  const letters = string.split('');
  let resultLetters = letters.map(letter=> {
    let result = letter == letter.toLowerCase() ? letter.toUpperCase() : letter.toLowerCase();
    return result;
  });
  return resultLetters.join('');
}

console.log(reverseCase('Happy Birthday!'));

  • Related