Moving every alphabet forward by 10 places in JavaScript


Problem

We are required to write a JavaScript function that takes in a string of English alphabets. Our function should push every alphabet forward by 10 places. And if it goes past 'z', we should start again at 'a'.

Example

Following is the code −

 Live Demo

const str = 'sample string';
const moveStrBy = (num = 10) => {
   return str => {
      const calcStr = (ch, code) => String
      .fromCharCode(code + (ch.charCodeAt(0) - code + num) % 26);
      const ACode = 'A'.charCodeAt(0);
      const aCode = 'a'.charCodeAt(0);
      return str.replace(/[a-z]/gi, ch => (
         ch.toLowerCase() == ch
         ? calcStr(ch, aCode)
         : calcStr(ch, ACode)
      ));
   };
};
const moveByTen = moveStrBy();
console.log(moveByTen(str));

Output

ckwzvo cdbsxq

Updated on: 17-Apr-2021

128 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements