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
版权声明:本文标题:javascript - Copy and paste indexed words maintaining unique index - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736544453a1944427.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论