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?
// 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(', ')}`;
});
#output {
margin-top: 10px;
padding: 10px;
border: 1px solid #ccc;
background: #f9f9f9;
}
<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>
2
Answers
I changed how the user interacts with the page because copy and paste seems awkward and messy. Clicking a button and then clicking the words is simpler and more intuitive.
Do the following in the example below:
<button>
.<button>
should turn blue and say: Edit Mode ON.<fieldset contenteditable>
.<output> <ol>
below.Details are commented in the example.