Highlight a word with jQuery

后端 未结 12 1391
粉色の甜心
粉色の甜心 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条回答
  •  旧时难觅i
    2020-11-22 02:00

    Here's a variation that ignores and preserves case:

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

提交回复
热议问题