Highlight a word with jQuery

后端 未结 12 1390
粉色の甜心
粉色の甜心 2020-11-22 01:20

I basically need to highlight a particular word in a block of text. For example, pretend I wanted to highlight the word "dolor" in this text:



        
12条回答
  •  面向向阳花
    2020-11-22 01:37

    Is it possible to get this above example:

    jQuery.fn.highlight = function (str, className)
    {
        var regex = new RegExp(str, "g");
    
        return this.each(function ()
        {
            this.innerHTML = this.innerHTML.replace(
                regex,
                "" + str + ""
            );
        });
    };
    

    not to replace text inside html-tags like , this otherwise breakes the page.

提交回复
热议问题