突出显示文本中的单词 [英] Highlight words in text

查看:35
本文介绍了突出显示文本中的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试选择一个单词,然后对其应用一些内容.示例如下.

I'm trying to select a single word, then apply something to it. Example as below.

<p>Some text here</p>

有没有办法选择文本这个词,然后对其应用一些东西?例如 .css() - 我知道您可以选择整个文本,然后选择第 2 个字,但这不是我想要做的.这个词可能有很多地方.

Is there a way to select the word text, then apply something to it? For example .css() - I know you can select the whole text, then select word number 2, but that's not what I'm trying to do. The word could be many places.

推荐答案

找到目标元素及其子元素,过滤它们的内容并搜索文本节点类型:

Find the target Element and its children, filter their contents and search for a textual nodeType:

var word = 'text';

var rgx = new RegExp('\\b('+word+')\\b', 'ig');

$('p, p *').contents().filter(function() {
  return this.nodeType === 3;
}).each(function() {
  $(this).replaceWith($(this).text().replace(rgx, '<span class="highlight">$1</span>'));
});

.highlight {
  background: gold;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Some text and a link <a href="text.html">text.html</a> here and <b>some bold text there</b>. Text Is Uppercase.<br>Text... text.<br>  Textual.</p>

我相信上面的内容应该很有希望,因为它不会使 HTML 崩溃,因为它不匹配属性字符串.

I believe the above should be quite promising since it'll not crash the HTML since it doesn't matches attributes strings.

这篇关于突出显示文本中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆