使用 JavaScript 中的算法加密字符串


问题

我们需要编写一个 JavaScript 函数,它接收一个字符串,并根据以下算法对其进行加密 −

  • 字符串仅包含以空格分隔的单词。
  • 我们需要使用以下规则对字符串中的每个单词进行加密 −
    • 第一个字母需要转换为其 ASCII 码。
    • 第二个字母需要与最后一个字母交换。

因此,根据此规则,字符串“good”将被加密为“103doo”。

示例

以下是代码 −

 在线演示

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));

输出

以下是控制台输出 −

103doo

更新于:20-Apr-2021

205 次浏览

开启你的 职业

通过完成课程获得认证

开始
广告
© . All rights reserved.