Encrypting a string based on an algorithm in JavaScript


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’.


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;


Following is the console output −