如何突出显示页面上与单词数组匹配的所有单词?

时间:2011-08-08 19:13:51

标签: jquery

我想在我的网页上找到与Javascript数组中的任何单词匹配的所有单词,并突出显示它们(将它们包装在特殊的span标签中)。最简单的方法是什么?我用jquery。

2 个答案:

答案 0 :(得分:3)

试试这些方法

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;
}

答案 1 :(得分:2)

不完美,但很简单,可能有效:

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/