首頁  >  文章  >  web前端  >  使用 JavaScript 基於演算法加密字串

使用 JavaScript 基於演算法加密字串

WBOY
WBOY轉載
2023-09-17 09:57:021188瀏覽

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

問題

我們需要寫一個JavaScript 函數,接收字串並根據以下演算法對其進行加密-

  • #字串僅包含空格分隔的單字。

  • 我們需要使用以下規則加密字串中的每個單字 -

    • #第一個字母需要轉換為 ASCII 碼。

    • 第二個字母需要與最後一個字母交換。

因此,根據此,字串「好」將被加密為「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

以上是使用 JavaScript 基於演算法加密字串的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除