Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
JavaScript function to accept a string and mirrors its alphabet
We need to write a function that accepts a string and mirrors its alphabet. This means each letter is replaced with its counterpart from the opposite end of the alphabet.
If the input is 'abcd' The output should be 'zyxw'
The function maps every character to the letter that is (26 - N) positions away from it, where N is the 1-based index of that alphabet (like 5 for 'e' and 10 for 'j').
How It Works
We use the String.prototype.replace() method to match all English alphabets regardless of case. For each letter:
- Get its ASCII code using
charCodeAt() - Determine if it's uppercase (65-90) or lowercase (97-122)
- Calculate the mirrored position and convert back to character
Example
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; // lowercase 'a'
end = 122; // lowercase 'z'
} else {
start = 65; // uppercase 'A'
end = 90; // uppercase 'Z'
}
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
Step-by-Step Breakdown
// Let's trace how 'A' becomes 'Z'
const char = 'A';
const ascii = char.charCodeAt(); // 65
const start = 65; // 'A'
const end = 90; // 'Z'
// Formula: end - (ascii - start)
const mirroredAscii = end - (ascii - start); // 90 - (65 - 65) = 90
const result = String.fromCharCode(mirroredAscii); // 'Z'
console.log(`${char} mirrors to ${result}`);
A mirrors to Z
Key Points
- The function preserves case - uppercase letters stay uppercase, lowercase stay lowercase
- Non-alphabetic characters remain unchanged
- Uses ASCII math to calculate mirror positions efficiently
- The regex
/[A-Za-z]/gmatches all letters globally
Conclusion
This mirror function creates a simple cipher by mapping each letter to its alphabetical opposite. It's useful for basic text transformation and demonstrates string manipulation with ASCII calculations.
Advertisements
