Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert Cases in a String

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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!'));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading