在 JavaScript 中交換字母與其後續字母


我們需要編寫一個 JavaScript 函式,該函式接收一個字串,並將字串中的每個字母從英文字母更改為其後續元素。

例如:如果字串是 −

const str = 'how are you';

輸出

那麼輸出應該為 −

const output = 'ipx bsf zpv'

因此,讓我們編寫此函式的程式碼 −

示例

其程式碼為 −

const str = 'how are you';
const isAlpha = code => (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
const isLast = code => code === 90 || code === 122;
const nextLetterString = str => {
   const strArr = str.split('');
   return strArr.reduce((acc, val) => {
      const code = val.charCodeAt(0);
      if(!isAlpha(code)){
         return acc+val;
      };
      if(isLast(code)){
         return acc+String.fromCharCode(code-25);
      };
      return acc+String.fromCharCode(code+1);
   }, '');
};
console.log(nextLetterString(str));

控制檯中的輸出為 −

ipx bsf zpv

更新於:2020 年 10 月 17 日

165 次瀏覽

開啟您的職業生涯

完成課程獲取證書

開始
廣告