{ &a"/> { &a">

Home  >  Article  >  Web Front-end  >  Encrypt strings based on algorithms using JavaScript

Encrypt strings based on algorithms using JavaScript

WBOY
WBOYforward
2023-09-17 09:57:021188browse

使用 JavaScript 基于算法加密字符串

Question

We need to write a JavaScript function that receives 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 ASCII code.

    • The second letter needs to be swapped with the last letter.

#So according to this, the string "good" will be encrypted to "103doo".

Example

The following is the code -

Live demonstration

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

The above is the detailed content of Encrypt strings based on algorithms using JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete