skip to Main Content

This is my method, it was returning the same string as the input.
for ex: toggleEveryCharCases(‘character’) => ‘character’

Please answer me guys…

export function toggleEveryCharCases(str: string): string {
  const strArr = str.split('');

  for (let i = 0; i < strArr.length; i++) {
    if (strArr[i] >= 'A' && strArr[i] <= 'Z') strArr[i] = strArr[i].toLowerCase();
    else if (strArr[i] >= 'a' && strArr[i] <= 'z') strArr[i] = strArr[i].toUpperCase();
  }

  return strArr.join('');
}

I have tried my best. I want to get the char case togggled string

2

Answers


  1. It does work as expected.

    function toggleEveryCharCases(str) {
      const strArr = str.split('');
    
      for (let i = 0; i < strArr.length; i++) {
        if (strArr[i] >= 'A' && strArr[i] <= 'Z') strArr[i] = strArr[i].toLowerCase();
        else if (strArr[i] >= 'a' && strArr[i] <= 'z') strArr[i] = strArr[i].toUpperCase();
      }
    
      return strArr.join('');
    }
    
    console.log(toggleEveryCharCases("StAcKoVeRfLoW"))

    you can simplify the code to be

    function toggleCase(str) {
      return str.split("")
         .map(ltr => ltr === ltr.toUpperCase() ? ltr.toLowerCase() : ltr.toUpperCase())
         .join("")
    }
    
    Login or Signup to reply.
  2. Here’s correct

    export function toggleEveryCharCases(str: string): string {
          
    const strArr = str.split('');
        
          for (let i = 0; i < strArr.length; i++) {
            if (strArr[i] >= 'A' && strArr[i] <= 'Z') {
              strArr[i] = strArr[i].toLowerCase();
            } else if (strArr[i] >= 'a' && strArr[i] <= 'z') {
              strArr[i] = strArr[i].toUpperCase();
            }
          }
        
          return strArr.join('');
        }
    console.log(toggleEveryCharCases('character'));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search