JavaScript function to accept a string and mirrors its alphabet


We have to write a function that accepts a string and mirrors its alphabet. For example −

If the input is ‘abcd’
The output should be ‘zyxw’

The function simply takes every character and map to the that is (26 - N) alphabets away from it, where is the 1 based index of that alphabet like 5 for e and 10 for j.

We will use the String.prototype.replace() method here, to match all the English alphabets irrespective of their case. The full code for this function will be −

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;
         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'));

Output

The output in the console will be −

ZYXW
Xzm dv uork gsrh zh dvoo
HLNV FKKVIXZHV HGFUU

Updated on: 25-Aug-2020

168 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements