How to shift each letter in the given string N places down in the alphabet in JavaScript?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are given a string of alphabets. Our task is to replace each of its alphabets with the alphabet that is n alphabets away from it in the English alphabet;

i.e.

if n = 1, replace a with b, replace b with c, etc (z would be replaced by a).

For example −

const str = "crazy";
const n = 1;

the output should be −

alphabeticShift(inputString) = "dsbaz".

Example

Following is the code −

const str = 'crazy';
const alphabeticShift = (str = '', n = 1) => {
   let arr = [];
   for(let i = 0; i < str.length; i++) {
      arr.push(String.fromCharCode((str[i].charCodeAt() + n)));
   }
   let res = arr.join("").replace(/{/g, 'a');;
   return res;
};
console.log(alphabeticShift(str));

Output

Following is the output on console −

dsbaz
raja
Published on 10-Dec-2020 07:52:00
Advertisements