Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

แยกสตริงเป็น 3 กลุ่ม: ตัวอักษร ตัวเลข สัญลักษณ์ - JavaScript

แยกสตริงออกเป็น 3 ส่วน: ตัวอักษร (Letters), ตัวเลข (Numbers), สัญลักษณ์พิเศษ (Special Characters) รักษาลำดับเดิม

ตัวอย่างโค้ด

const str = 'Th!s String C0nt@1ns d1fferent ch@ract5rs';

const separateCharacters = str => {
  return str.split('').reduce((acc, val) => {
    let { numbers, alpha, special } = acc;
    if (+val) { // ตัวเลข 0-9 (แต่ 0 จะเป็น falsy!)
      numbers += val;
    } else if (val.toUpperCase() !== val.toLowerCase()) {
      alpha += val; // มี upper/lower case แตกต่าง = ตัวอักษร
    } else {
      special += val;
    }
    return { numbers, alpha, special };
  }, { numbers: '', alpha: '', special: '' });
};

console.log(separateCharacters(str));

ผลลัพธ์

{
  numbers: '115',
  alpha: 'ThsStringCntnsdfferentchractrs',
  special: '! 0@ @'
}

ปัญหาของโค้ดต้นฉบับ

+val จะทำให้ '0' กลายเป็น 0 (falsy) → ตกไปกลุ่ม special ผิดพลาด

เวอร์ชันแก้ไข

const separateCharacters = str => {
  const result = { numbers: '', alpha: '', special: '' };
  
  for (const char of str) {
    if (/[0-9]/.test(char)) result.numbers += char;
    else if (/[a-zA-Z]/.test(char)) result.alpha += char;
    else result.special += char;
  }
  return result;
};

ใช้ Regex ทดสอบชัดเจน ไม่มีปัญหา falsy