繁体   English   中英

如何在 HTML 的一段文本中搜索一个短语,然后突出显示/着色?

[英]How would I search for a phrase in a section of text in HTML and then highlight/color it?

我已经看到了很多类似的问题,但我似乎无法弄清楚在我的情况下如何确切地了解它。 本质上,我有三个不同的变量:article、arg1、arg2。 文章是一个大约 5 个句子长的字符串。 Arg1 和 arg2 是文章中的一个句子/短语。 我将把这篇文章作为网站上的基本 < p > 标签。 但我希望文章中的 arg1 和 arg2 是不同的颜色或突出显示或其他东西,所以很明显它在文章中的位置。 我将如何 go 搜索 < p > 标签中的文本,找到每个参数,然后更改特定文本的样式?

用正则表达式替换很有用:

 let str = document.getElementById("str"); let result; result = str.innerHTML.replace(/Lorem Ipsum/gi, `<span class="my-span">Lorem Ipsum</span>`).replace(/specimen book/gi, `<span class="my-span">specimen book</span>`); str.innerHTML = result; console.log(str);
 p.my-span { color: red; font-weight: bold }
 <p id="str">Lorem Ipsum is simply dummy text of the printing and specimen book typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, Lorem Ipsum but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,Lorem Ipsum and more recently with desktop specimen book publishing software like Aldus PageMaker including versions of Lorem Ipsum</p>

通过将段落分成块并遍历变量的出现以在它们周围添加<mark></mark>标记,应该不难实现。

这可以改进,但一个简单的例子是这样的:

 let arg = "dummy"; let paragraph = document.getElementById('paragraph'); let broken = paragraph.innerHTML.split(arg); paragraph.innerHTML = ''; broken.map((part, i) => { paragraph.innerHTML += i + 1 >= broken.length? part: part + ' <mark>' + arg + '</mark>'; });
 <p id="paragraph">this is just a dummy text and like any other dummy text it does nothing besides being dummy</p>

编辑

Emy 的解决方案确实更优雅:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM