在 JavaScript 中重組字串中的字元


問題

我們需要編寫一個 JavaScript 函式,該函式接受一個字串 str 作為第一個也是唯一的引數。

字串 str 可以包含三種類型的字元 −

  • 英文字母:(A-Z)、(a-z)

  • 數字:0-9

  • 特殊字元 − 所有其他剩餘字元

我們的函式應迭代此字串並構建一個數組,該陣列恰好包含三個元素,第一個包含字串中出現的所有字母,第二個包含數字,第三個包含特殊字元,保持字元的相對順序。我們最終應該返回此陣列。

例如,如果輸入函式為

輸入

const str = 'thi!1s is S@me23';

輸出

const output = [ 'thisisSme', '123', '! @' ];

示例

以下是程式碼 −

 線上演示

const str = 'thi!1s is S@me23';
const regroupString = (str = '') => {
   const res = ['', '', ''];
   const alpha = 'abcdefghijklmnopqrstuvwxyz';
   const numerals = '0123456789';
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      if(alpha.includes(el) || alpha.includes(el.toLowerCase())){
         res[0] += el;
         continue;
      };
      if(numerals.includes(el)){
         res[1] += el;
         continue;
      };
      res[2] += el;
   };
   return res;
};
console.log(regroupString(str));

輸出

[ 'thisisSme', '123', '! @' ]

更新於:2021 年 4 月 24 日

82 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.