เราต้องเขียนฟังก์ชั่นที่ยอมรับสตริงและสะท้อนตัวอักษรของมัน ตัวอย่างเช่น −
If the input is ‘abcd’ The output should be ‘zyxw’
ฟังก์ชันนี้นำอักขระและแผนที่ทุกตัวไปยังตัวอักษร (26 - N) ที่อยู่ห่างจากมัน โดยที่ดัชนี 1 ของตัวอักษรนั้น ๆ เช่น 5 สำหรับ e และ 10 สำหรับ j
เราจะใช้วิธี 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