

Ask HN: Efficient HTML Text Replace, RegEx? jQuery? - jdavid

[disclaimer]
I understand the risk in using a framework, but I also understand the benefits.  I was only using jQuery to see if it was a fast enough approach.<p>So, the other day, i wrote a line of jQuery like so to find all elements that contained the word 'apple'.  the idea was that i could do the find/replace faster than doing it via a regex over the whole doc, which requires a redraw.<p>$("*:contains['apple']").each(
 function(){
   //do something
 });<p>the result was that i was processing iteratively on every item in the DOM that had a descendant which contained the word 'apple', rather than just the child objects.<p>I ended up using some code from Johann Burkard
http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html<p>Johann's approach iterates through the text using a string.indexOf(pat) pattern.  i was wondering if any of you had any better ideas?<p>In the ideal situation, i would use a jQuery selector to select only child nodes that contained 'apple', but there is no such selector 'isChild' that can be paired with :contains as far as i know.<p>I would like to replace all instances of 'apple' with '&#60;span class="highlight"&#62;apple&#60;/span&#62;" with the lowest impact to the dom possible.
======
byoung2
_but there is no such selector 'isChild' that can be paired with :contains as
far as i know_

Maybe you can use $.children()? Something like:

    
    
      $('div').children(":contains('apple')").each(function() {
        var html = $(this).html().replace(/apple/,"<b>apple</b>");
        $(this).html(html);
      });
    

example: <http://www.fillerspace.com/apple.html>

~~~
jdavid
this doesn't seem to work to well on a complex page like
<http://techcrunch.com/2010/07/29/apple-location/> .

~~~
byoung2
Just a few small changes fixes it:

    
    
      jQuery('div.entry').find(":contains('apple')").each(function() {
        var html = jQuery(this).html().replace(/apple/gi,"<span class='apple'>Apple</span>");
        jQuery(this).html(html);
      });
    

I made the str.replace global and case-insensitive (/apple/gi), and changed
$.children() to $.find() since on TC the content wasn't the direct descendant
of a div. $.find() goes more than one level down. They also seem to be using
jQuery.noConflict() so I changed the $ to jQuery.

example: <http://fillerspace.com/techcrunch.html>

