简体   繁体   English

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

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

I've seen a lot of similar questions but I can't seem to figure out exactly how to go about it in my situation.我已经看到了很多类似的问题,但我似乎无法弄清楚在我的情况下如何确切地了解它。 Essentially, I have three different variables: article, arg1, arg2.本质上,我有三个不同的变量:article、arg1、arg2。 Article is a string that is about 5 sentences long.文章是一个大约 5 个句子长的字符串。 Arg1 and arg2 is a sentence/phrase in the article. Arg1 和 arg2 是文章中的一个句子/短语。 I'm going to have the article as a basic < p > tag on the website.我将把这篇文章作为网站上的基本 < p > 标签。 But I want arg1 and arg2 within the article to be a different color or highlighted or something, so it's obvious where in the article it is.但我希望文章中的 arg1 和 arg2 是不同的颜色或突出显示或其他东西,所以很明显它在文章中的位置。 How would I go about searching through the text in the < p > tag, finding each argument, and then changing the style of specific text?我将如何 go 搜索 < p > 标签中的文本,找到每个参数,然后更改特定文本的样式?

replace with regex is useful:用正则表达式替换很有用:

 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>

shouldn't be hard to achieve by splitting the paragraph into chunks and iterate through occurrences of the variables to add <mark></mark> tag around them.通过将段落分成块并遍历变量的出现以在它们周围添加<mark></mark>标记,应该不难实现。

this can be improved but a simple example would be something like:这可以改进,但一个简单的例子是这样的:

 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>

Edit编辑

Emy's solution is more elegant indeed:) Emy 的解决方案确实更优雅:)

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

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