Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tạo định dạng ABC-1234 với Regular Expression JavaScript

Định dạng chuỗi theo mẫu ABC-1234

Sử dụng Regular Expression (Regex) kết hợp String.replace() để chèn dấu gạch ngang giữa chữ cái và số.

Ví dụ minh họa

<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Format ABC-1234</title>
    <style>
        body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 20px; }
        .formatting { font-size: 24px; font-weight: bold; font-family: monospace; padding: 10px; background: #f5f5f5; display: inline-block; }
        button { padding: 8px 16px; margin-left: 10px; cursor: pointer; }
    </style>
</head>
<body>
    <h1>Định dạng ABC-1234 với Regex</h1>
    <p class="formatting" id="text">ABC1234</p>
    <button id="btnFormat">ĐỊNH DẠNG</button>

    <script>
        const textEl = document.getElementById('text');
        const btn = document.getElementById('btnFormat');

        // Hàm callback cho replace
        function insertDash(match, g1, g2, g3, g4, g5) {
            // Regex có 2 pattern: (\d{3})(\d{3})(\d{4}) HOẶC ([A-Z]{3})(\d{4})
            if (g1) {
                // Pattern số: 3-3-4
                return [g1, g2, g3].join('-');
            } else {
                // Pattern chữ+số: 3-4
                return [g4, g5].join('-');
            }
        }

        btn.addEventListener('click', () => {
            const original = textEl.textContent;
            // Regex: 3 số-3 số-4 số HOẶC 3 chữ HOA-4 số
            const formatted = original.replace(
                /^(\d{3})(\d{3})(\d{4})|([A-Z]{3})(\d{4})$/,
                insertDash
            );
            textEl.textContent = formatted;
            btn.textContent = formatted === original ? 'ĐỊNH DẠNG' : 'ĐÃ ĐỊNH DẠNG';
        });
    </script>
</body>
</html>

Giải thích Regex

/^(\d{3})(\d{3})(\d{4})|([A-Z]{3})(\d{4})$/

// Nhánh 1: Số điện thoại dạng 10 chữ số
^(\d{3})(\d{3})(\d{4})
  │     │     │
  │     │     └─ Group 3: 4 số cuối
  │     └─────── Group 2: 3 số giữa
  └──────────── Group 1: 3 số đầu

// Nhánh 2: Mã dạng ABC1234
|([A-Z]{3})(\d{4})$
  │      │
  │      └──── Group 5: 4 số
  └────────── Group 4: 3 chữ HOA

Cách tiếp cận đơn giản hơn (khuyến nghị)

Thay vì regex phức tạp với callback, tách thành 2 trường hợp rõ ràng:

function formatCode(str) {
    // Trường hợp 1: 3 chữ + 4 số -> ABC-1234
    if (/^[A-Z]{3}\d{4}$/.test(str)) {
        return str.slice(0, 3) + '-' + str.slice(3);
    }
    // Trường hợp 2: 10 số -> 123-456-7890
    if (/^\d{10}$/.test(str)) {
        return str.slice(0, 3) + '-' + str.slice(3, 6) + '-' + str.slice(6);
    }
    return str; // Không khớp pattern
}

console.log(formatCode('ABC1234'));    // ABC-1234
console.log(formatCode('1234567890')); // 123-456-7890
console.log(formatCode('abc1234'));    // abc1234 (không khớp, chữ thường)

Mở rộng: Định dạng linh hoạt

// Hàm chung: chèn separator sau N ký tự
function chunkString(str, size, separator = '-') {
    return str.match(new RegExp(`.{1,${size}}`, 'g')).join(separator);
}

console.log(chunkString('ABC1234', 3));      // ABC-123-4 (3 ký tự)
console.log(chunkString('1234567890', 3));   // 123-456-789-0
console.log(chunkString('1234567890', 4));   // 1234-5678-90