How do you highlight all the words on the page that match an array of words?

风格不统一 提交于 2021-02-18 18:13:04

问题


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.


回答1:


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/




回答2:


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


来源:https://stackoverflow.com/questions/6987328/how-do-you-highlight-all-the-words-on-the-page-that-match-an-array-of-words

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!