ปัญหา
เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริง str เป็นอาร์กิวเมนต์เดียว
สตริง str อาจมีตัวอักษร 3 ประเภท:
ตัวอักษรภาษาอังกฤษ: (A-Z), (a-z)
ตัวเลข: 0-9
อักขระพิเศษ - อักขระที่เหลือทั้งหมด
ฟังก์ชันควรวนลูปผ่านสตริงและสร้างอาร์เรย์ที่มี 3 สมาชิก ตัวแรกมีตัวอักษรทั้งหมด ตัวที่สองมีตัวเลข ตัวที่สามมีอักขระพิเศษ รักษาลำดับสัมพัทธ์ของตัวอักษร คืนอาร์เรย์นี้
ตัวอย่างเช่น หากอินพุตคือ
Input
const str = 'thi!1s is S@me23';
Output
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', '! @' ]