Encrypting a string based on an algorithm using JavaScript


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

103doo

Updated on: 20-Apr-2021

579 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements