在 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP