javascript 如何使用java脚本突出显示div中特定字符串的所有出现?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11790375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:20:53  来源:igfitidea点击:

how to highlight all the occurrence of a particular string in a div with java script?

javascripthtml

提问by Samy

i need to highlight all the occurrences of a string in particular div by selecting a string, once i select a word and click a button it need to highlight all its occurrence inside a div,

我需要通过选择一个字符串来突出显示一个字符串在特定 div 中的所有出现,一旦我选择一个单词并单击一个按钮,它需要突出显示它在一个 div 中的所有出现,

eg - if i select

例如 - 如果我选择

cricket is game

板球是游戏

it should highlight all the occurrences of cricket is game some may be like this cricketis game or cricketis game

它应该突出显示所有出现的板球是比赛,有些可能就像这个 板球是比赛或板球是比赛

enter image description here

在此处输入图片说明

采纳答案by Tim Down

You can get the browser to do the hard work for you using a TextRangein IE and window.find()in other browsers.

您可以让浏览器TextRange在 IE 和window.find()其他浏览器中使用 a 为您完成繁重的工作。

This answershows how to do it. It will match text that crosses element boundaries and does the highlighting for you using document.execCommand().

这个答案显示了如何做到这一点。它将匹配跨越元素边界的文本并使用document.execCommand().

Alternatively, James Padolsey recently published a script that I haven't used but looks like it could help: http://james.padolsey.com/javascript/replacing-text-in-the-dom-solved/

或者,James Padolsey 最近发布了一个我没有使用过但看起来有帮助的脚本:http: //james.padolsey.com/javascript/replacing-text-in-the-dom-solved/

回答by Sandeep Muthangi

mark.jsseems pretty good for this. Here's my 3 line fiddle to take an html 'string' and highlight the search string.

mark.js似乎很适合这个。这是我的 3 行小提琴,用于获取 html“字符串”并突出显示搜索字符串。

$(document).ready(function() {
    var html_string = "<b>Major Tom to groundcontrol.</b> Earth is blue <span> and there's something </span> i can do";

    var with_highlight = $("<div/>").html(html_string).mark("can");

    $("#msg").html(with_highlight);
})

Link to jsfiddle

链接到 jsfiddle

回答by Pranay Rana

You can tryout this script

你可以试试这个脚本

Demo

演示

highlightSearchTermshighlightSearchTerms这个脚本的功能中,var bodyText = document.body.innerHTML;var bodyText = document.body.innerHTML;被你的除法替换,然后它会为你完成任务..

/*
 * This is the function that actually highlights a text string by
 * adding HTML tags before and after all occurrences of the search
 * term. You can pass your own tags if you'd like, or if the
 * highlightStartTag or highlightEndTag parameters are omitted or
 * are empty strings then the default <font> tags will be used.
 */
function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag) 
{
  // the highlightStartTag and highlightEndTag parameters are optional
  if ((!highlightStartTag) || (!highlightEndTag)) {
    highlightStartTag = "<font style='color:blue; background-color:yellow;'>";
    highlightEndTag = "</font>";
  }

  // find all occurences of the search term in the given text,
  // and add some "highlight" tags to them (we're not using a
  // regular expression search, because we want to filter out
  // matches that occur within HTML tags and script blocks, so
  // we have to do a little extra validation)
  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 {
      // skip anything inside an HTML tag
      if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
        // skip anything inside a <script> block
        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;
}
/*
 * This is sort of a wrapper function to the doHighlight function.
 * It takes the searchText that you pass, optionally splits it into
 * separate words, and transforms the text on the current web page.
 * Only the "searchText" parameter is required; all other parameters
 * are optional and can be omitted.
 */
function highlightSearchTerms(searchText, treatAsPhrase, warnOnFailure, highlightStartTag, highlightEndTag)
{
  // if the treatAsPhrase parameter is true, then we should search for 
  // the entire phrase that was entered; otherwise, we will split the
  // search string so that each word is searched for and highlighted
  // individually
  if (treatAsPhrase) {
    searchArray = [searchText];
  } else {
    searchArray = searchText.split(" ");
  }

  if (!document.body || typeof(document.body.innerHTML) == "undefined") {
    if (warnOnFailure) {
      alert("Sorry, for some reason the text of this page is unavailable. Searching will not work.");
    }
    return false;
  }

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

  document.body.innerHTML = bodyText;
  return true;
}

/*
 * This displays a dialog box that allows a user to enter their own
 * search terms to highlight on the page, and then passes the search
 * text or phrase to the highlightSearchTerms function. All parameters
 * are optional.
 */
function searchPrompt(defaultText, treatAsPhrase, textColor, bgColor)
{
  // This function prompts the user for any words that should
  // be highlighted on this web page
  if (!defaultText) {
    defaultText = "";
  }

  // we can optionally use our own highlight tag values
  if ((!textColor) || (!bgColor)) {
    highlightStartTag = "";
    highlightEndTag = "";
  } else {
    highlightStartTag = "<font style='color:" + textColor + "; background-color:" + bgColor + ";'>";
    highlightEndTag = "</font>";
  }

  if (treatAsPhrase) {
    promptText = "Please enter the phrase you'd like to search for:";
  } else {
    promptText = "Please enter the words you'd like to search for, separated by spaces:";
  }

  searchText = prompt(promptText, defaultText);

  if (!searchText)  {
    alert("No search terms were entered. Exiting function.");
    return false;
  }

  return highlightSearchTerms(searchText, treatAsPhrase, true, highlightStartTag, highlightEndTag);
}

回答by Flash

This should get you started: http://jsfiddle.net/wDN5M/

这应该让你开始:http: //jsfiddle.net/wDN5M/

function getSelText() {
  var txt = '';
  if (window.getSelection) {
    txt = window.getSelection();
  } else if (document.getSelection) {
        txt = document.getSelection();
  } else if (document.selection) {
    txt = document.selection.createRange().text;
  }
  document.getElementById('mydiv').innerHTML = document.getElementById('mydiv').innerHTML.split(txt).join('<span class="highlight">' + txt + '</span>');
}

See: Get selected text on the page (not in a textarea) with jQuery

请参阅:使用 jQuery 在页面上(而不是在 textarea 中)获取选定的文本

If you want it to work across element boundaries your code will need to be more involved than this. jQuerywill make your life easier when doing the necessary DOM traversal and manipulation.

如果您希望它跨越元素边界工作,您的代码将需要比这更多地参与。在进行必要的 DOM 遍历和操作时,jQuery将使您的生活更轻松。

回答by Vladislav Qulin

First you need to find needed substrings in needed text and wrap them with <span class="search-highlight">. Every time you need to highlight another strings, you just get all the .search-highlight spans and turn their outerHtml into innerHtml. So the code will be close to:

首先,您需要在需要的文本中找到需要的子字符串,并用 <span class="search-highlight"> 包裹它们。每次您需要突出显示另一个字符串时,您只需获取所有 .search-highlight 跨度并将它们的 outerHtml 转换为 innerHtml。所以代码将接近:

function highLight(substring, block) {
   $(block).find(".search-highlight").each(function () {
      $(this).outerHtml($(this).html());
   });
   // now the block is free from previous highlights

   $(block).html($(block).html().replace(/substring/g, '<span class="search-highlight">' + substring + '</span>'));
}

回答by Robban1980

I would use jQuery to iterate over all Elements in your div (Don't know if you have other elements in the div) and then a Regular Expression and do a greedy match to find all occurrences of the selected string in your text(s) in the elements.

我将使用 jQuery 遍历 div 中的所有元素(不知道 div 中是否还有其他元素),然后使用正则表达式并进行贪婪匹配以查找文本中所有出现的所选字符串在元素中。

回答by Andr

Much better to use rather JavaScript str.replace() function then window.find() to find all occurrences of a filter value. Iterating through the whole page might be bit complicated but if you want to search within a parent div, or within a table str.replace() is just simpler.

最好使用 JavaScript str.replace() 函数而不是 window.find() 来查找所有出现的过滤器值。遍历整个页面可能有点复杂,但如果你想在父 div 中或表中搜索 str.replace() 就更简单了。

In your example you have only one DIV, that is even simpler. Here is what I would do (having your DIV an ID: myDIV):

在您的示例中,您只有一个 DIV,这更简单。这是我会做的(让你的 DIV 有一个 ID:myDIV):

        //Searching for "District Court"
        var filter = "District Court";  

        //Here we create the highlight with html tag: <mark> around filter
        var span = '<mark>' + filter + '</mark>';

        //take the content of the DIV you want to highlight
        var searchInthisDiv =   document.getElementById("MyDiv");
        var textInDiv       =   searchInthisDiv.innerHTML;

        //needed this var for replace function, do the replace (the highlighting)
        var highlighted     =   textInDiv.replace(filter,span); 
        textInDiv.innerHTML =   highlighted;

The trick is to replace the search string with a span that is having the filter within a tag. str.replace replaces all occurrences of the search string, so no need to bother with looping. Loop can be used to loop through DIVs or other DOM elements.

诀窍是用在标签内具有过滤器的跨度替换搜索字符串。str.replace 替换所有出现的搜索字符串,因此无需担心循环。循环可用于遍历 DIV 或其他 DOM 元素。

回答by user2169140

<form id=f1 name="f1" action="" 
onSubmit="if(this.t1.value!=null && this.t1.value!='')
findString(this.t1.value);return false"
>
<input type="text" id=t1 name=t1size=20>
<input type="submit" name=b1 value="Find">
</form>
<script>
var TRange=null;

function findString (str) {
 if (parseInt(navigator.appVersion)<4) return;
 var strFound;
 if (window.find) {

  // CODE FOR BROWSERS THAT SUPPORT window.find

  strFound=self.find(str);
  if (!strFound) {
   strFound=self.find(str,0,1);
   while (self.find(str,0,1)) continue;
  }
 }
 else if (navigator.appName.indexOf("Microsoft")!=-1) {

  // EXPLORER-SPECIFIC CODE

  if (TRange!=null) {
   TRange.collapse(false);
   strFound=TRange.findText(str);
   if (strFound) TRange.select();
  }
  if (TRange==null || strFound==0) {
   TRange=self.document.body.createTextRange();
   strFound=TRange.findText(str);
   if (strFound) TRange.select();
  }
 }
 else if (navigator.appName=="Opera") {
  alert ("Opera browsers not supported, sorry...")
  return;
 }
 if (!strFound) alert ("String '"+str+"' not found!")
 return;
}
</script>