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-09-16

582 次瀏覽

開啟職業生涯

透過完成課程並獲得認證

入門
廣告
© . All rights reserved.