用 JavaScript 交替切換字串大小寫


我們需要編寫一個 JavaScript 函式,該函式接收一個字串,並構建一個新字串,其中原始字串中的所有大寫字元都轉換成小寫,原始字串中的所有小寫字元都轉換成大寫。

例如:如果字串是 -

const str = 'The Case OF tHis StrinG Will Be FLiPped';

輸出

那麼輸出應該是 -

const output = 'tHE cASE of ThIS sTRINg wILL bE flIpPED';

示例

對應的程式碼如下 -

const str = 'The Case OF tHis StrinG Will Be FLiPped';
const isUpperCase = char => char.charCodeAt(0) >= 65 && char.charCodeAt(0)<= 90;
const isLowerCase = char => char.charCodeAt(0) >= 97 && char.charCodeAt(0) <= 122;
const flipCase = str => {
   let newStr = '';
   const margin = 32;
   for(let i = 0; i < str.length; i++){
      const curr = str[i];
      if(isLowerCase(curr)){
         newStr += String.fromCharCode(curr.charCodeAt(0) - margin);
      }else if(isUpperCase(curr)){
         newStr += String.fromCharCode(curr.charCodeAt(0) + margin);
      }else{
         newStr += curr;
      };
   };
   return newStr;
};
console.log(flipCase(str));

輸出

控制檯中的輸出 -

tHE cASE of ThIS sTRINg wILL bE flipped

更新於: 2020 年 10 月 15 日

937 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始吧
廣告
© . All rights reserved.