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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP