6 ms·
Ask HN: Efficient HTML Text Replace, RegEx? jQuery?
[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.
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.
$("*:contains['apple']").each(
function(){
//do something
});
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.
I ended up using some code from Johann Burkard
http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
Johann's approach iterates through the text using a string.indexOf(pat) pattern. i was wondering if any of you had any better ideas?
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.
I would like to replace all instances of 'apple' with '<span class="highlight">apple</span>" with the lowest impact to the dom possible.
- byoung2 16y agobut 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 http://www.fillerspace.com/apple.html
- jdavid 16y agothis doesn't seem to work to well on a complex page like http://techcrunch.com/2010/07/29/apple-location/ http://techcrunch.com/2010/07/29/apple-location/ .
- byoung2 16y agoJust 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 http://fillerspace.com/techcrunch.html