Replace alphabets with nth forward alphabet in JavaScript


We are required to write a JavaScript function that takes in an alphabet string and a number, say n. We should then return a new string in which all the characters are replaced by respective alphabets at position n alphabets next to them.

For example, if the string and the number are −

const str = 'abcd';
const n = 2;

Then the output should be −

const output = 'cdef';

Example

The code for this will be −

const str = 'abcd';
const n = 2;
const replaceNth = (str, n) => {
   const alphabet = 'abcdefghijklmnopqrstuvwxyz';
   let i, pos, res = '';
   for(i = 0; i < str.length; i++){
      pos = alphabet.indexOf(str[i]);
      res += alphabet[(pos + n) % alphabet.length];
   };
   return res;
};
console.log(replaceNth(str, n));

Output

And the output in the console will be −

cdef

Updated on: 20-Nov-2020

319 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements