0

In a nutshell, I'm working on a JavaScript function that does the following:

  1. Loops through the words in a page.
  2. Looks for a match from an array using a regex.
  3. If there's a match, it attaches a <span> element to the word (which has a yellow background).

The following is the script and a sample HTML text to run the script on:

function highlight(elem, keywords) {
  keywords.sort((a, b) => b.length - a.length);
  
  Array.from(elem.childNodes).forEach(child => {
    const keywordRegex = new RegExp(keywords.join('|'), 'gi'); 
    if (child.nodeType !== 3) { // not a text node
      highlight(child, keywords, 'gi');
    } else if (keywordRegex.test(child.textContent)) {
      const frag = document.createDocumentFragment();
      let lastIdx = 0;
      child.textContent.replace(keywordRegex, (match, idx) => {
        const part = document.createTextNode(child.textContent.slice(lastIdx, idx));
        const highlighted = document.createElement('span');
        highlighted.textContent = match;
        highlighted.style.backgroundColor = 'yellow';
        frag.appendChild(part);
        frag.appendChild(highlighted);
        lastIdx = idx + match.length;
      });
      const end = document.createTextNode(child.textContent.slice(lastIdx));
      frag.appendChild(end);
      child.parentNode.replaceChild(frag, child);
    }
  });
}

let noGoWords = ["lorem", "adip", "ipsum", "consec"];

highlight(document.querySelector('#wrapper'), noGoWords);
<div id="wrapper">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque placerat pretium urna, quis ullamcorper nisl. Quisque pulvinar rutrum nunc in ultricies. Fusce vulputate pretium enim non tincidunt. Donec efficitur sem a consectetur fringilla. Ut sagittis nisi sed mollis porta. Morbi condimentum urna dui, id pharetra massa venenatis in. Praesent at placerat lorem. Mauris suscipit ligula ut facilisis efficitur. Aliquam rutrum consectetur tristique. Cras semper, neque vel fermentum fringilla, odio magna cursus felis, quis ullamcorper felis metus eget quam. Integer at efficitur arcu, sit amet luctus neque. Pellentesque eleifend, velit quis hendrerit imperdiet, augue enim maximus velit, non sodales est enim eu mi. Mauris sed sem et neque molestie vulputate ut at risus. Praesent arcu enim, laoreet et blandit sollicitudin, porta ut sem. Sed vulputate ligula ac massa ultrices sollicitudin.
<p/>
<div>

While I managed to have the RegEx ignore capitalized words, I want the script to highlight full words only, not part of words. For example, the script should highlight "lorem" and "ipsum", but not "adip" and "consec" because they're only present in the sample text as parts of words.

Thus, do you know how I can edit the regex so that it highlights full-words only?

Thanks in advance for your replies!

d_z90
  • 1,213
  • 2
  • 19
  • 48

0 Answers0