Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

javascript - 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 you'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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...