接受字符串并对其字母镜像的 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