I stumbled upon a fantastic script on a programming forum that almost fits my requirements perfectly. It essentially replaces specific words in a document with links to Wikipedia. However, I have run into an issue where I only want the first occurrence of a word to be linked.
Here is the script (sourced from this particular response):
function replaceInElement(element, find, replace) {
// logic to handle replacements and child nodes
}
function replaceInText(text, find, replace) {
// code to replace text content with specified links
}
// defining keywords for matching purposes using regex
var find= /\b(keyword|whatever)\b/gi;
replaceInElement(document.body, find, function(match) {
// creating wikipedia links based on matched keywords
});
I attempted to tweak the script by utilizing indexOf instead of regular expressions following guidance from another solution (referenced in this answer). The goal was to improve speed efficiency:
var words = ["keyword","whatever"];
var text = "Whatever, keywords are like so, whatever... Unrelated, I now know " +
"what it's like to be a tweenage girl. Go Edward.";
var matches = [];
var lowerCaseText = text.toLowerCase();
for (var i=0;i<words.length;i++) {
if (lowerCaseText.indexOf(words[i]) != -1)
matches.push(words[i]);
}
My query is how can I merge these two scripts to achieve optimal speed without relying on external libraries?