JavaScript函数接受字符串并镜像其字母
我们必须编写一个接受字符串并镜像其字母的函数。例如-
If the input is ‘abcd’ The output should be ‘zyxw’
该函数只是简单地获取每个字符并映射到远离它的(26-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