Home > Web Front-end > JS Tutorial > body text

Encrypt strings based on algorithms using JavaScript

WBOY
Release: 2023-09-17 09:57:02
forward
1237 people have browsed it

使用 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));
Copy after login

Output

103doo
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template