在 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', '! @' ]
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP