Switch between uppercase to lowercase


Posted by Christy on 2022-04-21

Description: Write a function named swap that accepts a string and return uppercase letters exchange to lowercase letters and vice versa.

function swap(str) {
  let result = "";
  for (let i = 0; i < str.length; i++) {
    if (str[i] >= "A" && str[i] <= "Z") {
      result += str[i].toLowerCase();
      // above line is not equal to below two lines
      // str[i].toLowerCase();
      // result += str[i];
    } else {
      result += str[i].toUpperCase();
    }
  }
  return result;
}

console.log(swap("Peter")); // pETER
console.log(swap("AbCdE")); // aBcDe
console.log(swap("34dE")); // 34De
console.log(swap("!!222")); // !!222

The exclamation and number would maintain the same in both toLowerCase() or toUpperCase().










Related Posts

七天學會 swift - 基礎篇 Day2

七天學會 swift - 基礎篇 Day2

【閱讀】注意力商人:他們如何操弄人心?揭密媒體、廣告、群眾的角力戰

【閱讀】注意力商人:他們如何操弄人心?揭密媒體、廣告、群眾的角力戰

[ 筆記 ] OOP - 物件導向基礎概念

[ 筆記 ] OOP - 物件導向基礎概念


Comments