Help with custom cloze parser

I’ve attempted to write a card template for incremental Cloze revealing that also supports incremental Cloze revealing within MathJax equations. I tried to circumvent Anki’s inbuilt Cloze by only using {{Field}} (without cloze:: prefix). This returns only the raw content of the field without Anki’s pre-template translation. Then I tried to implement my own cloze parser.

This is the code I have:

<!-- Front Side -->
<div class="card">
    <div class="front" id="front">{{Content}}</div>
    <div class="back" id="back"></div>
</div>

<script>
    // Function to parse cloze deletions
    function parseCloze(text) {
        var clozeRegex = /{{c(\d+) ::.+?}}/g;
        return text.replace(clozeRegex, function(match, index) {
            return '<span class="cloze" data-index="' + index + '">[...]</span>';
        });
    }

    // Function to reveal cloze deletions incrementally
    function revealCloze() {
        var clozes = document.querySelectorAll('.cloze');
        clozes.forEach(function(cloze) {
            var index = cloze.getAttribute('data-index');
            cloze.innerHTML = '{{c' + index + '::' + cloze.innerHTML.substring(5, cloze.innerHTML.length - 6) + '}}';
        });
    }

    // Initialize
    document.addEventListener('DOMContentLoaded', function() {
        var front = document.getElementById('front');
        var back = document.getElementById('back');
        
        // Parse cloze deletions in the front content
        front.innerHTML = parseCloze(front.innerHTML);
        
        // Click event to reveal cloze deletions
        front.addEventListener('click', function() {
            revealCloze();
            back.innerHTML = front.innerHTML;
            front.style.display = 'none';
            back.style.display = 'block';
        });
    });
</script>

But its returning:
Front template has a problem:
Found ‘⁨{{c(\d+) ::.+?}}⁩’, but there is no field called ‘⁨.+?⁩’

Please could I grab some help from someone with better JavaScript skills, as I’m completely out of my depth. There doesn’t seem to be any other incremental cloze reveal addon/script that supports MathJax!

1 Like