简体   繁体   中英

regexp finds html tags

I wrote a simple 'search function' using jQuery. you type some text in a box and it returns the text on the page you searched. However, if I type the word 'the' the search results come back with <thead></thead> with 'the' highlighted. How can I make it so it doesn't find html tags like those? A similar thing happens when I type 'edit' and it returns an image named 'edit....' with the image disappeared and 'edit' highlighted.

I tried a few different things with the line starting with element, as I think that's where the problem lies.

        function highliter(word, id){
            $('*').removeClass('highlight');
            var rgxp = new RegExp(word, 'g');
            var repl = '<span class="highlight">' + word + '</span>';
            var element = document.getElementById(id);
            element.innerHTML = element.innerHTML.replace(/word/g, repl);
            // element.innerHTML = element.innerHTML.replace(rgxp, repl);

            $('html, body').scrollTop($(".highlight").offset().top - 126);

Well. To be honest, I'm not 100% satisfied with this solution, but it does the job and hopefully will give you some ideas.

It works in two steps:

  • first process text nodes of all elements that contain the target word and replace it with a special markup (which should be unlikely to be found anywhere else in the source code -- this is the hack that I'm not very happy with)
  • then replace our markup with the final replacement pattern, using a regular expression and the html() method (this part is very similar to your original one)

 function highliter(word, id) { var el = $('#' + id); var repl = '<span class="highlight">' + word + '</span>'; $('*').removeClass('highlight'); recursiveMarker(word, el); el.html(el.html().replace(/\\[MY_MARKUP\\]/g, repl)); } function recursiveMarker(word, parent) { var rgxp = new RegExp(word, 'g'); var repl = '[MY_MARKUP]'; parent.find(':contains(' + word + ')').contents().each(function(key, el) { if(this.nodeType == 3) { el.data = el.data.replace(rgxp, repl); } else { recursiveMarker(word, $(el)); } }); } highliter('div', 'container'); 
 .highlight { background-color:#ffff00; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="container"> <div>This is a div <span id="div">with a span whose id is 'div'</span></div> <div>This is another div</div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM