javascript index jan 7th 2025

by Julian

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Word Index Tracker</title>
    <style>
        textarea {
            width: 45%;
            height: 200px;
            margin: 10px;
            display: inline-block;
            vertical-align: top;
        }
        #output {
            width: 90%;
            height: 150px;
            margin: 10px;
            display: block;
        }
    </style>
</head>
<body>
    <h2>Text Document</h2>
    <textarea id="documentArea" placeholder="Type or paste your document here..."></textarea>

    <h2>Paste Area</h2>
    <textarea id="pasteArea" placeholder="Paste text here to track..."></textarea>

    <h2>Indexed Words</h2>
    <textarea id="output" readonly></textarea>
    </body>
</html>

JavaScript

const documentArea = document.getElementById('documentArea');
        const pasteArea = document.getElementById('pasteArea');
        const output = document.getElementById('output');

        let wordIndex = {}; // Tracks word indices

        // Function to index words in the document
        function indexWords(text) {
            const words = text.match(/\b\w+\b/g) || [];
            words.forEach((word, i) => {
                word = word.toLowerCase(); // Normalize case
                if (!wordIndex[word]) {
                    wordIndex[word] = [];
                }
                wordIndex[word].push(i + 1); // Record position (1-based index)
            });
        }

        // Function to update the output area
        function updateOutput() {
            const outputLines = [];
            for (const [word, positions] of Object.entries(wordIndex)) {
                outputLines.push(`${word}: ${positions.join(', ')}`);
            }
            output.value = outputLines.join('\n');
        }

        // Event listener for paste events in the paste area
        pasteArea.addEventListener('paste', (event) => {
            const pasteData = (event.clipboardData || window.clipboardData).getData('text');
            indexWords(pasteData); // Index pasted words
            updateOutput(); // Update the output
        });

        // Optional: Monitor documentArea for initial indexing
        documentArea.addEventListener('input', () => {
            wordIndex = {}; // Reset the index
            indexWords(documentArea.value);
            updateOutput();
        });