admin管理员组

文章数量:1123099

I am trying to figure how to index every word in a text box and maintain these indexes when the text is copy and pasted (into another text area). The problem I am facing is giving each word a unique index even if the word is duplicated.

Currently javascript is duplicating indexes for duplicate words. These words actually each have a unique timecode saved in a database which I later on want to retrieve but can't do this if there are duplicate indexes.

The aim is to allow users to copy and paste portions of text and then construct a list on indexes from their selections. How can I make sure each words gets a unique index? I made a fiddle

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>
        #output {
            margin-top: 10px;
            padding: 10px;
            border: 1px solid #ccc;
            background: #f9f9f9;
        }
    </style>
</head>
<body>
    <h1>Word Index Tracker</h1>
    <p>Original Text: <span id="original-text"></span></p>
    <textarea id="text-box" rows="5" cols="50" placeholder="Paste text here to see indexes"></textarea>
    <div id="output">Indexes will appear here...</div>
    </body>
</html>

Javascript

// Original string
        const originalString = "As you can see the script does not give unique indexes to words that are duplicated in the script. The gets the same index throughout the script.";
        document.getElementById('original-text').innerText = originalString;

        // Create a map of words to their indexes
        const wordIndexMap = {};
        originalString.split(/\s+/).forEach((word, index) => {
            wordIndexMap[word] = index;
        });

        // Textbox and output elements
        const textBox = document.getElementById('text-box');
        const output = document.getElementById('output');

        // Event listener for tracking changes in the text box
        textBox.addEventListener('input', () => {
            const pastedWords = textBox.value.split(/\s+/);
            const indexes = pastedWords
                .filter(word => word in wordIndexMap) // Only track words that are in the original text
                .map(word => wordIndexMap[word]); // Map to their indexes

            // Display the indexes
            output.innerText = `Indexes of words: ${indexes.join(', ')}`;
        });

本文标签: javascriptCopy and paste indexed words maintaining unique indexStack Overflow