Encrypting a string based on an algorithm in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a string and encrypts it based on the following algorithm −

  • The string contains only space separated words.
  • We need to encrypt each word in the string using the following rules −
    • The first letter needs to be converted to its ASCII code.
    • The second letter needs to be switched with the last letter.

Therefore, according to this, the string ‘good’ will be encrypted as ‘103doo’.

Example

Following is the code −

 Live Demo

const str = 'good';
const encyptString = (str = '') => {
   const [first, second] = str.split('');
   const last = str[str.length - 1];
   let res = '';
   res += first.charCodeAt(0);
   res += last;
   for(let i = 2; i < str.length - 1; i++){
      const el = str[i];
      res += el;
   };
   res += second;  
   return res;
};
console.log(encyptString(str));

Output

Following is the console output −

103doo
raja
Published on 20-Apr-2021 08:24:54
Advertisements