Replication behavior Ctrl + F

I want to consolidate all the information about the word in the document. To do this, I wrote the following code:

function highlight_search_param() { // get the search_param from location.search filters = location.search.substr(1).split('&') search_param = '' for (i in filters) { param = filters[i].split('=') if (param[0] == 'q') { search_param = param[1]; break; } } if (search_param == '') return True alert(search_param) // convert into many possible cases title_search_param = search_param = search_param[0].toUpperCase() + search_param.substring(1) $('.summary-block').contents().find(':contains("'+search_param+'"),:contains("'+search_param.toLowerCase()+'"),:contains("'+title_search_param+'"),:contains("'+search_param.toUpperCase()+'")').each(function(){ if($(this).text().indexOf(search_param)>=0) { $(this).html($(this).text().replace(search_param, "<span class='highlight'>" + search_param +"</span>")); } }) } 

Now that I have finished writing text() , the span is displayed as text. (Obviously)

If I write html() , there is a possibility that there are other elements (brothers and sisters of this node text) that can be erased.

Note.

  • on the $('.summary-block ) page
  • the search must be case insensitive , but the replacement must remain unchanged in this case
  • there may be more than one occurrence within the summary block
search_param

Basically, I'm looking for something similar to ctrl+F browser behavior

(FIDDLE) [http://jsfiddle.net/bYhxs/]

+4
source share
1 answer

Why not do something like:

 $(".summary-block").each(function () { $(this).html(function (index, oldHTML) { return oldHTML.replace( search_param, "<span style='color:green;'>" + search_param + "</span>"); }); }); 

Js fiddle

This code is smaller, and it only looks at the text of the element, not HTML.

Edit: according to the comments, I updated this to work with more than one .summary-block element.

EDIT : according to your new edit. See the above script. Basically, you create a RegExp object and specify a template instead.

 var pattern = new RegExp(search_param, 'gi'); //.. replace(pattern, "<span style='color:green;'>" + search_param +"</span>") ..// 

See this post for more information:

Case-insensitive javascript replaces regular expression with account word boundary

It is worth noting that you do not need everything that contains verification now. Just use this final code:

 var search_param = "seaRching"; var pattern = new RegExp(search_param, 'gi'); $(".summary-block").each(function(){ $(this).html($(this).html().replace( pattern, "<span class='highlight'>" + search_param +"</span>" ) ); }); 

Updated violin

+3
source

Source: https://habr.com/ru/post/1486363/


All Articles