jQuery find text and show as bold in html page

Updated at 31-Aug-2021, By samar

jQuery find text and show as bold in html page

We’ll attempt to use programming in this lesson to solve the "jQuery find text and show as bold in html page" puzzle.

You can find text and show as bold in html page using jQuery. You have to pass the words to method which you want to make bold or highlight in html page.
  • JQuery find text and highlight in html page

    <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Optio temporibus, voluptate libero consequatur aut ullam accusamus officia minus, minima ratione quasi vero qui tenetur quam enim repellat, cum ipsa saepe.</p>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <script>
    $.fn.wrapInTag = function(opts) {
    var tag = opts.tag || 'strong',
        words = opts.words || [],
        regex = RegExp(words.join('|'), 'gi'),
        replacement = '<'+ tag +'>$&</'+ tag +'>';
        return this.html(function() {
            return $(this).text().replace(regex, replacement);
        });
    };
    
    $('p').wrapInTag({
        tag: 'strong',
        words: ['consectetur']
    });
    </script>
    <!-- Output: -->
    <!-- <p>Lorem, ipsum dolor sit amet <strong>consectetur</strong> adipisicing elit. Optio temporibus, voluptate libero consequatur aut ullam accusamus officia minus, minima ratione quasi vero qui tenetur quam enim repellat, cum ipsa saepe</p> -->
    

    This code snippet will help you to find out the specified text which you want to highlight or make it bold in html page. You can pass tag name to tag and words with comma separated to words in wrapInTag() method.

Back to code snippet queries related jquery