เราต้องเขียนฟังก์ชันที่รับสตริงและกระจกอักษรอักษรของมัน ตัวอย่าง −
ถ้าอินพุตคือ 'abcd' ผลลัพธ์ควรเป็น 'zyxw'
ฟังก์ชันแค่นำตัวอักษรแต่ละตัวไปแมปกับตัวที่ห่างออกไป (26 - N) ตำแหน่ง โดย N คือดัชนี 1-based ของอักษรนั้น เช่น 5 สำหรับ e และ 10 สำหรับ j
เราจะใช้ String.prototype.replace() ที่นี่ เพื่อจับคู่อักษรอังกฤษทุกตัวไม่สนใจ case โค้ดเต็มสำหรับฟังก์ชันนี้จะเป็น −
ตัวอย่าง
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