Replace text but not the HTML tags?
I'm doing text matching on an Autocomplete in JQuery, by overloading the _renderItem method to check the JSON object for the text the user searched for. Upon finding it, I'm replacing it with a span tag with a "user_highlight_match" class.
I'm doing multi word searching, so "John Smi" would highlight John, then Smi, and searching "John James Smi" would highlight "John" and "Smi". The problem with this is that, say you search for "John Las", it will start matching against the class attribute of the span tag, if it's already there. How can I get around this?
Edit: Here's some code showing what I'm talking about:
renderItem = function(ul, item) {
li = $('<li>', id: item._id);
if this.term and not item.dialog
terms = this.term.split(' ');
for term in terms
re = new RegExp("("+term+")", 'i');
match = re.exec(item.name);
if match
item.name = item.name.replace re, "<span class=\"user_highlight_match\">+match[0]+</span>";
)
So the first term will match fine, but every time around after that, if yo开发者_StackOverflowu're searching for anything in the html tags, the partial match is replaced with a tag. So say there was a match on "las", it would become this:
<span c<span class="user_highlight_match">Last</span>s="user_highlight_match">Last</span>
You'll have to search text nodes and replace them with the html you want. See this question: Find word in HTML.
Edit: Here's a jQuery version of my answer there.
http://jsfiddle.net/gilly3/auJkG/
function searchHTML(searchString, htmlString) {
var expr = new RegExp(searchString, "gi");
var container = $("<div>").html(htmlString);
var elements = container.find("*").andSelf();
var textNodes = elements.contents().not(elements);
textNodes.each(function() {
var matches = this.nodeValue.match(expr);
if (matches) {
var parts = this.nodeValue.split(expr);
for (var n = 0; n < parts.length; n++) {
if (n) {
$("<span>").text(matches[n - 1]).insertBefore(this);
}
if (parts[n]) {
$(document.createTextNode(parts[n])).insertBefore(this);
}
}
$(this).remove();
}
});
return container.html();
}
精彩评论