After someone searches for something on my site, i highlight the searched term in the list of results.
For example, if you search for "Lorem", you'll get an article with the title "Lorem ipsum dolor sit amet" as one of the results, where "Lorem" will be highlighted because that's your searched words and the other words will be in normal font.
My function is currently this:
function highlightSearchedTerm(term) {
var regex = new RegExp('('+term+')', 'gi');
$('.markable').each(function(){
var content = $(this).html();
var replaced = content.replace(regex, "<span class=\"highlight\">$1</span>");
$(this).html(replaced);
});
}
Problem is in the text of the article there can be some HTML code, like links, images etc, so if someone searches for "click", then an onclick attribute of a link will be replaced and i get a span inside the link.
Like
<a href="http://www.example.com" onclick="window.open(this.href);return false;">link</a>
will get replaced and i'll get
<a href="http://www.example.com" on<span class="highlight">click</span>="window.open(this.href);return false;">link</a>
which is bad.
How do i avoid that?