3

I want to find all the words on my webpage that match any of the words in a Javascript array, and highlight them (wrap them in special span tags). What's the easiest way to do this? I use jquery.

dan
  • 43,914
  • 47
  • 153
  • 254

2 Answers2

3

Try this these methods

highlightWord(["text1", "text2"]);


function highlightWord(searchArray, container)
{
  var bodyText;
  if(container)
     bodyText = container.html();
  else
     bodyText = $(document.body).html();

  container = container || $(document.body);

  for (var i = 0; i < searchArray.length; i++) {
    bodyText = doHighlight(bodyText, searchArray[i]);
  }

  container.html(bodyText);

  return true;
}

function doHighlight(bodyText, searchTerm) 
{

    var highlightStartTag = "<span style='color:blue; background-color:yellow;'>";
    var highlightEndTag = "</span>";

  var newText = "";
  var i = -1;
  var lcSearchTerm = searchTerm.toLowerCase();
  var lcBodyText = bodyText.toLowerCase();

  while (bodyText.length > 0) {
    i = lcBodyText.indexOf(lcSearchTerm, i+1);

    if (i < 0) {
      newText += bodyText;
      bodyText = "";
    } else {
      if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
        if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) {
          newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;

          bodyText = bodyText.substr(i + searchTerm.length);

          lcBodyText = bodyText.toLowerCase();

          i = -1;

        }

      }

    }

  }

  return newText;
}
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
3

Not perfect, but simple and may work:

var regex = /(Hello|Goodbye)/g;

$('*').each(function() {
    var $this = $(this);
    var text = $this.text();
    if (regex.test(text)) {
        $this.html(
            $this.html().replace(regex, '<span>$1</span>')
        );
    }
});

http://jsfiddle.net/pdWAn/

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
  • 1
    Awesome answer. I used a modified regex to: 1. Ignore case "i" at the end. 2. Only match the word if it is a separate word. For example, searching for "to" will be found if the text contains the words "to" and "history". I get around this by adding "\b" before and after each word. Full regex as an example: `var wordsToReplace = /(\bof\b|\bour\b|\bfrom\b|\bto\b|\bat\b)/gi;` Ugly, but it gets the job done. – Damon Bauer May 16 '13 at 13:04