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

Cách đếm số lần xuất hiện ký tự trong chuỗi JavaScript

Duyệt chuỗi đếm ký tự khớp. Có nhiều cách từ cơ bản đến hiện đại.

Ví dụ

<!DOCTYPE html>
<html>
<body>
    <script>
        function countChar(str, char) {
            // Cách 1: split + filter (ES6)
            return str.split('').filter(c => c === char).length;
            // Cách 2: regex (global)
            // return (str.match(new RegExp(char, 'g')) || []).length;
            // Cách 3: reduce
            // return [...str].reduce((acc, c) => acc + (c === char), 0);
        }
        console.log(countChar("hello world", "l")); // 3
        console.log(countChar("JavaScript", "a"));  // 2
    </script>
    <!-- Demo UI -->
    <input type="text" id="strInput" placeholder="Nhập chuỗi" value="hello world"><br><br>
    <input type="text" id="charInput" placeholder="Ký tự" maxlength="1" value="l"><br><br>
    <button onclick="showCount()">Đếm</button>
    <p id="result"></p>
    <script>
        function showCount() {
            const str = document.getElementById('strInput').value;
            const char = document.getElementById('charInput').value;
            if (!char) return alert("Nhập ký tự!");
            document.getElementById('result').textContent = "Kết quả: " + countChar(str, char);
        }
    </script>
</body>
</html>