Computer >> Computer tutorials >  >> Programming >> Javascript

Encrypting a string JavaScript


We are required to write a JavaScript function that takes in a string as the first argument and a number as the second argument.

The function should substitute each alphabet of the string by shifting it up the alphabet by the given number.

The shifting should wrap around back to the beginning or end of the alphabet, like a should follow z instead of undefined or any void result.

Example

const str = 'this is a str';
const encryptString = (str = '', num = 1) => {
   const alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
   str = str.toLowerCase();
   let res = "";
   for (let i = 0; i < str.length; i++) {
      const letter = str[i];
      if (alphabet.indexOf(letter) === -1) {
         res += letter;
         continue;
      }
   let index = alphabet.indexOf(letter) + num % 26;
   if (index > 25){
      index -= 26;
   };
   if (index < 0){
      index += 26;
   };
   if(str[i] === str[i].toUpperCase()){
      res += alphabet[index].toUpperCase();
      }else{ res += alphabet[index];
      };
   }
   return res;
};
console.log(encryptString(str, 4));

Output

And the output in the console will be −

xlmw mw e wxv