JS gist 页面上高亮显示搜索字符

39 min read
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;
}

浏览器原生方法

$(document.body).html() # 获取指定容器html文本内容
container.html(bodyText); # 设置指定容器的html文件内容

字符串函数

  • lastIndexOf 该方法将从尾到头地检索字符串 str,看它是否含有子串 searchValue。开始检索的位置在字符串的 fromIndex 处或字符串的结尾(没有指定 fromIndex 时)。如果找到一个 searchValue,则返回 searchValue 的第一个字符在 str 中的位置。str中的字符位置是从 0 开始的。
  • toLowerCase 更改大小写
  • **substring() **方法返回一个字符串在开始索引到结束索引之间的一个子集, 或从开始索引直到字符串的末尾的一个子集。