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

Lặp qua các kết quả khớp Regex trong JavaScript

Giới thiệu

Khi dùng Regular Expression với cờ g (global), có thể lặp qua tất cả các kết quả khớp bằng matchAll() (ES2020) hoặc exec() trong vòng lặp.

Các phương pháp

1. String.matchAll() - Khuyến nghị (ES2020)

const text = 'cat, bat, rat, mat';
const regex = /\w+at/g;

for (const match of text.matchAll(regex)) {
    console.log(match[0], 'tại vị trí', match.index);
}
// cat tại 0, bat tại 5, rat tại 10, mat tại 15

2. RegExp.exec() trong vòng lặp (Cũ)

const regex = /\w+at/g;
let match;
while ((match = regex.exec(text)) !== null) {
    console.log(match[0], 'tại', match.index);
}

3. String.match() - Chỉ lấy giá trị khớp

const matches = text.match(/\w+at/g);
// ['cat', 'bat', 'rat', 'mat'] - không có index

Ví dụ hoàn chỉnh

<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Regex matchAll</title>
    <style>
        body { font-family: 'Segoe UI', sans-serif; padding: 20px; }
        .sample { font-size: 16px; color: #d32f2f; font-weight: 500; padding: 15px; background: #ffebee; border-radius: 4px; }
        .result { font-size: 16px; color: #6a1b9a; font-weight: 500; margin-top: 15px; padding: 15px; background: #f3e5f5; border-radius: 4px; min-height: 100px; white-space: pre-wrap; }
        button { padding: 10px 20px; background: #1976d2; color: white; border: none; border-radius: 4px; cursor: pointer; }
    </style>
</head>
<body>
    <h1>Lặp qua các khớp Regex</h1>
    <div class="sample" id="sample">Có một con mèo nằm cạnh gậy cricket và đuổi theo con chuột</div>
    <div class="result" id="result"></div>
    <button id="btn">TÌM TỪ KẾT THÚC BẰNG "at"</button>
    <h3>Nhấn nút để tìm các từ kết thúc bằng 'at'</h3>

    <script>
        const sampleEle = document.getElementById('sample');
        const resultEle = document.getElementById('result');
        const btn = document.getElementById('btn');

        btn.addEventListener('click', () => {
            const text = sampleEle.textContent;
            const regex = /\w+at/gi; // i: không phân biệt hoa thường
            
            resultEle.textContent = '';
            let count = 0;
            
            for (const match of text.matchAll(regex)) {
                count++;
                resultEle.textContent += `${count}. "${match[0]}" tại vị trí ${match.index}\n`;
            }
            
            if (count === 0) {
                resultEle.textContent = 'Không tìm thấy từ nào kết thúc bằng "at"';
            }
        });
    </script>
</body>
</html>

Kết quả

Văn bản: "Có một con mèo nằm cạnh gậy cricket và đuổi theo con chuột"
Kết quả (case-insensitive):

1. "mèo" tại vị trí 10
2. "gậy" tại vị trí 22
3. "chuột" tại vị trí 42

Ứng dụng thực tế

// Trích xuất tất cả email
const emails = text.matchAll(/[\w.+-]+@[\w-]+\.[\w.-]+/g);

// Thay thế có điều kiện
const result = text.replace(/\d+/g, (match) => Number(match) * 2);

// Parse log entries
const logRegex = /(\d{4}-\d{2}-\d{2}) (\w+): (.+)/g;
for (const [, date, level, msg] of logText.matchAll(logRegex)) {
    console.log({ date, level, msg });
}