javascript - 根据与另一个字符串的匹配突出显示文本

标签 javascript jquery

我试图根据文本是否与从数据库接收的字符串匹配来突出显示文本。为了说明这个问题,这里有一个例子。 鉴于此文本:

<div class='text'>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>

这段文字:

<div id='matchingHighlight'>
Lorem ipsum <!-- Highlight this text within <div id='text'></div> !-->
</div>

如何突出显示 .text 中与 #matchingHighlight (Lorem ipsum) 中的文本匹配的文本?

最佳答案

要“突出显示”关键字/短语,您需要将其包裹在任何内联元素周围。我建议您使用 <span>标签。

以下逻辑将用 span 内包含的相同文本替换文本。类别为 .highlight 的标签

$(document).ready(function() {
    var $text = $('.text');
    var textToHighlight = $('#matchingHighlight').text().trim();
    var textCurrent = $text.html().trim();
    var isTextExists = textCurrent.indexOf(textToHighlight) > -1;

    if(isTextExists) {
        textCurrent = textCurrent.replace(textToHighlight, "<span class='highlight'>" + textToHighlight + "</span>");
        $text.html(textCurrent);
    }
});

然后您可以使用 css 对其进行样式设置,例如

.highlight {
    background: yellow;
}

https://pastebin.com/vaB3wa96

关于javascript - 根据与另一个字符串的匹配突出显示文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57565950/

相关文章:

javascript - 提交多个复选框值

javascript - 如何将 Prop 从父级传递给子级再到子级的子级?

javascript - 如何在文档数组中搜索字符串数组

jQuery Slider 不拾取换行符上的元素

javascript - 将文件从 Apache 提供给 Javascript

javascript - tinyMCE textarea focusout 事件?

javascript - Jquery fadeIn fadeOut 在 IE8 中不工作,但在 chrome,firefox 中工作

javascript - 属性 'success' 不存在 - jQuery

javascript - 为什么 jQuery(document).on('click... 不注册对特定 div 的点击?

javascript - 如何延迟切换变量的值?