stack2
by Julian
HTML
<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>
CSS
#output {
margin-top: 10px;
padding: 10px;
border: 1px solid #ccc;
background: #f9f9f9;
}
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;
function e( originalString ) {
let words = originalString.split(/\s+/);
let wordIndexMap = words[ 0 ];
for( let i = 1; i < words.length; i++ ) {
// this line makes the difference, here we make sure that there are
// no repeated words.
if( ! wordIndexMap.includes( words[ i ] )) wordIndexMap += " " + words[ i ];
}
words = wordIndexMap.split(/\s+/);
let out = [ words.length ];
for( let i = 1; i < words.length; i++ ) {
out[ i ] = i;
}
return out;
}
const textBox = document.getElementById('text-box');
const output = document.getElementById('output');
textBox.addEventListener('input', () => {
// Display the indexes
output.innerText = `Indexes of words: ${e(textBox.value) .join(', ')}`;
});