将字符串中找到的单词替换为大小写敏感(搜索和高亮显示)

Replacing a found word within the string to case (in)sensitive (search and highlight)

本文关键字:搜索 大小写敏感 高亮 显示 替换 字符串 单词      更新时间:2023-09-26

我已经采取了别人的荧光笔代码,我正试图修改它,使其为我的项目工作。总的来说,代码工作得很好,但是在显示结果方面有一个小问题。高亮笔查找指定的单词并将元素中的整个文本替换为指定的关键字。

所以在这个例子中,如果我想在句子"cat is an awesome pet"中突出一个单词"cat",我得到的结果是"cat is an awesome pet"。总是使用大写很容易,但这样做的问题是所需的单词可能在句子中的不同位置。例如:我爱我的猫。

我想做的是让脚本记住之前的区分大小写的状态,在高亮显示它之后,我想让它显示之前指定的大写或小写。

我在表函数中搜索关键字,找到关键字后应该突出显示它。

// highlighter func
    function highlight_words(word, element) {
        if(word){
            var textNodes;
            word = word.replace(/'W/g, '');
            var str = word.split(" ");
            $(str).each(function(){
                var term = this;
                var textNodes = $(element).contents().filter(function(){ return this.nodeType === 3 });
                textNodes.each(function() {
                    var content = $(this).text();
                    var regex = new RegExp(term, "gi");
                    content = content.replace(regex, '<span class="highlight">' + term + '</span>');
                    $(this).replaceWith(content);
                });
            });
        }
    }

如何触发函数

//search_inp is the keyword entered in the text input field such as "Cat"
highlight_words(search_inp, $("#FoundElem table tbody .perm-name a"));

显示什么

<div id="FoundElem">
<table cellspacing="1" class="perm-table" id="table0000">
<tbody><tr class="row4" id="temp0">
    <td class="perm-name"><a title=""><span class="highlight">cat</span> is an awesome pet</a></td>
</tr></tbody>
</table>
</div>

我能够做到这一点的方式是通过添加CSS大写到所有的关键字。它适用于我的情况,但对于您想要保留前一个值的情况,它将不起作用。

无论如何,这是一个css,最终帮助我。

.highlight {
    background-color:yellow;
    text-transform:capitalize;
}