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

Thuộc tính lastIndex trong JavaScript Regex

Khái niệm

lastIndex là thuộc tính của đối tượng RegExp (khi có cờ g hoặc y) chỉ vị trí bắt đầu tìm kiếm tiếp theo. Giá trị này tự động cập nhật sau mỗi lần exec() hoặc test() thành công.

Đặc điểm

    g (global) hoặc y (sticky)
  • Được cập nhật tự động bởi exec(), test()
  • Có thể gán thủ công để reset hoặc thay đổi vị trí tìm kiếm
  • Reset về 0 khi không còn khớp

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>Regex lastIndex</title>
    <style>
        body { font-family: 'Segoe UI', sans-serif; padding: 20px; }
        .sample { font-size: 18px; font-weight: 500; color: #d32f2f; padding: 15px; background: #ffebee; border-radius: 4px; }
        .result { font-size: 16px; font-weight: 500; color: #333; margin-top: 15px; padding: 15px; background: #f5f5f5; border-radius: 4px; white-space: pre-wrap; }
        button { padding: 10px 20px; background: #1976d2; color: white; border: none; border-radius: 4px; cursor: pointer; }
    </style>
</head>
<body>
    <h1>Thuộc tính lastIndex trong JavaScript</h1>
    <div class="sample" id="sample">Vua mua một chiếc nhẫn đắt tiền.</div>
    <div class="result" id="result"></div>
    <button id="btn">TÌM "ing"</button>
    <h3>Nhấn nút để tìm chỉ số của 'ing' trong chuỗi</h3>

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

        // Regex với cờ 'g' - BẮT BUỘC
        const regex = new RegExp('ing', 'g');
        
        // Lần đầu test để thiết lập lastIndex
        regex.test(sampleEle.textContent);

        btn.addEventListener('click', () => {
            const found = regex.test(sampleEle.textContent);
            if (found) {
                resultEle.textContent += `✅ "ing" tìm thấy - lastIndex = ${regex.lastIndex}\n`;
            } else {
                resultEle.textContent += `❌ Không tìm thấy thêm - lastIndex reset về ${regex.lastIndex}\n`;
                // Reset thủ công để tìm lại từ đầu
                regex.lastIndex = 0;
            }
        });
    </script>
</body>
</html>

Kết quả

Chuỗi: "Vua mua một chiếc nhẫn đắt tiền." (tiếng Anh: "The king bought an expensive ring.")

Lần 1: "ing" tìm thấy - lastIndex = 14 (sau "buy**ing**")
Lần 2: "ing" tìm thấy - lastIndex = 30 (sau "r**ing**.")
Lần 3: Không tìm thấy - lastIndex = 0 (reset)

Ứng dụng nâng cao

1. Tìm tất cả vị trí khớp

function findAllPositions(str, regex) {
    const positions = [];
    let match;
    while ((match = regex.exec(str)) !== null) {
        positions.push({ value: match[0], index: match.index });
    }
    return positions;
}

2. Tokenizer đơn giản

const tokenizer = /\w+|[^\w\s]/g;
const text = "Hello, world!";
let token;
while ((token = tokenizer.exec(text)) !== null) {
    console.log(`Token: "${token[0]}" tại ${token.index}`);
}
// Token: "Hello" tại 0
// Token: "," tại 5
// Token: "world" tại 7
// Token: "!" tại 12

3. Cảnh báo: lastIndex bị chia sẻ

const regex = /abc/g;
regex.test('abc'); // true, lastIndex=3
regex.test('abc'); // false! lastIndex=3, không khớp ở vị trí 3
regex.lastIndex = 0; // Phải reset
regex.test('abc'); // true

Khuyến nghị: Dùng matchAll() (ES2020) thay vì quản lý lastIndex thủ công.