Every word includes a start, end, and also returns as text. My goal is to enclose each word within an <a>
tag while highlighting them individually.
identifyComplexWords(text, words) {
// list of "complex words"
const complexWords = words;
// array to store results
const results = [];
// loop through each complex word and search for occurrences in the text
let match, regexp;
for (let i = 0; i < complexWords.length; i++) {
// the current complex word being checked
const complexWord = complexWords[i];
regexp = new RegExp(complexWord, 'g');
while ((match = regexp.exec(text)) !== null) {
// create result object
const result = {
begin: (regexp.lastIndex - complexWords[i].length),
end: regexp.lastIndex,
text: complexWord
};
// add the result object to the array
const index = results.length;
results[index] = result;
console.log(results[index]);
}
}
// return the results array
return results;
}
The output of this function would be:
{begin: 6, end: 11, text: "Lorem"}
{begin: 112, end: 117, text: "Lorem"}
{begin: 218, end: 223, text: "Lorem"}
I have a function that wraps words in an <a>
tag and highlights them, here is the function:
highlightSelection() {
this.identifyComplexWords(this.postIWant, this.theHardWords);
const userSelection = window.getSelection();
if (userSelection.toString() === null) {
return;
} else {
for (let i = 0; i < userSelection.rangeCount; i++) {
this.highlightRange(userSelection.getRangeAt(i));
this.word = userSelection.toString();
}
}
}
guidGenerator() {
const S4 = () => {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
};
return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4());
}
highlightRange(range) {
const newNode = document.createElement('a');
newNode.id = this.guidGenerator();
newNode.className = 'annotation_class';
newNode.setAttribute(
'style',
'background-color: yellow; display: inline;'
),
range.surroundContents(newNode);
this.viewAnnotation(newNode.id);
}
Although the above function works manually, I need to automate it when running the identifyComplexWords
function for each word to be enclosed within an <a>
tag and highlighted.
If anyone has any suggestions on how to achieve this, I would greatly appreciate it. Thank you in advance!