How to highlight all text occurrences in a HTML page with JavaScript?

后端 未结 4 1487
逝去的感伤
逝去的感伤 2020-12-09 09:40

I really thought this would have been answered years ago, still I did not find any solution:

I want to highlight (i.e. make a colored background) all occurrences of

相关标签:
4条回答
  • 2020-12-09 10:05

    The best option for doing this is usually, somewhat surprisingly, to not do it.

    Rely instead on the built-in search feature of the web browser: This ensures that users have a consistent experience, and saves you a lot of trouble in having to double the work that has already been done to allow for this.

    0 讨论(0)
  • 2020-12-09 10:08

    I struggled to find a robust text highlighter that duplicates the browsers ctrl + f functionality for months. I've used a host of jQuery plugins. Some are better than others but none are capable of spanning HTML. Say you want to find text that includes a link - the browser can do it but no jQuery plugins I've found can.

    Turns out bare naked javascript has the answer. Just window.find().

    find(string, matchcase, searchBackward)
    

    string : The text string for which to search.

    matchcase : Boolean value. If true, specifies a case-sensitive search. If you supply this parameter, you must also supply backward.

    searchBackward : Boolean. If true, specifies a backward search. If you supply this parameter, you must also supply casesensitive.

    It highlights html laden strings and it's compatible with every browser you care about. Read more about it at http://www.w3resource.com/javascript/client-object-property-method/window-find.php

    The unfortunate thing is you can't seem to do anything with it. I can't wrap it in styled span tags, get the position, scroll to it or change the highlight colour. I'm still looking for the ideal ctrl + f JS function.

    0 讨论(0)
  • 2020-12-09 10:18

    Window.find() should do the job.

    Although it is not standardised yet, almost all major newer-version browsers support it, such as Google Chrome, Firefox, IE, Safari, Opera, and browsers on iPhone/Android/Amazon Fire tablets and phones, etc.

    Below is a sample implementation:

    /*
     * Search for text in the window ignoring tags
     * 
     * Parameters:
     *     text: a string to search for
     *     backgroundColor: 
     *         "yellow" for example, when you would like to highlight the words
     *         "transparent", when you would like to clear the highlights
     * */
    function doSearch(text, backgroundColor) {
        if (window.find && window.getSelection) {
            document.designMode = "on";
            var sel = window.getSelection();
            sel.collapse(document.body, 0);
    
            while (window.find(text)) {
                document.execCommand("HiliteColor", false, backgroundColor);
                sel.collapseToEnd();
            }
            document.designMode = "off";
        }
    }
    

    The code is from Tim Down' implementation using Window.find()

    Before the search, the HTML text looks like:

    <p>Here is some searchable text with some lápices in it, and some
        <b>for<i>mat</i>t</b>ing bits, and a URL
        <a href="https://www.google.com">Google Search Engine</a> as a link.
    </p>
    

    Once you've search for text, for example, some lápices in it, and some formatting bits, and a URL Google, the HTML text will change to:

    <p>Here is some searchable text with <span style="background-color: yellow;">some lápices in it, and some
        <b>for<i>mat</i>t</b>ing bits, and a URL
        </span><a href="https://www.google.com"><span style="background-color: yellow;">Google </span>Search Engine</a> as a link.
    </p>
    

    See the code on jsfiddle.

    0 讨论(0)
  • 2020-12-09 10:24

    If you are trying to highlight the search terms from google then you can use this jquery plugin available at https://github.com/hail2u/jquery.highlight-search-terms

    If you want functionality like chrome. you can use this code.

    $(document).ready(function(){
      var search = ['p', 'div', 'span'];
    
      $("#highlighter").bind('keyup', function(e){
        var pattern = $(this).val();
    
        $.each(search, function(i){
            var str = search[i];        
            var orgText = $(str).text();
    
            orgText = orgText.replace(pattern, function($1){
              return "<span style='background-color: red;'>" + $1 + "</span>"
            });
    
            $(str).html(orgText);
        });    
      });
    });
    
    0 讨论(0)
提交回复
热议问题