接受字串並對其字母映象的 JavaScript 函式
我們需要編寫一個函式,它接受一個字串並對其字母映象。例如:
If the input is ‘abcd’ The output should be ‘zyxw’
該函式簡單地採用每個字元,並將其對映到距離它 26 個字母(N)之外的字母,其中 N 為該字母的基於 1 的索引,例如 e 的索引為 5,j 的索引為 10。
我們將在此處使用 String.prototype.replace() 方法,以匹配所有英文字母,無論其大小寫如何。此函式的完整程式碼為:
示例
const str = 'ABCD';
const mirrorString = str => {
const regex = /[A-Za-z]/g;
return str.replace(regex, char => {
const ascii = char.charCodeAt();
let start, end;
if(ascii > 96){
start = 97;
end = 122;
} else {
start = 65;
end = 90;
}
return String.fromCharCode(end - (ascii-start));
});
}
console.log(mirrorString(str));
console.log(mirrorString('Can we flip this as well'));
console.log(mirrorString('SOME UPPERCASE STUFF'));輸出
控制檯中的輸出為:
ZYXW Xzm dv uork gsrh zh dvoo HLNV FKKVIXZHV HGFUU
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP