【问题标题】:how to highlight specific text in a string displayed in a div?如何突出显示在 div 中的字符串中的特定文本?
【发布时间】:2021-12-12 03:52:20
【问题描述】:
<div
style={{ color: "white" }}
dangerouslySetInnerHTML={{
__html: `text <i style="color: red" >some data </i> not interesting`,
}}
/>
所以这是一种将字符串转换为html元素的方法。
这不是我想要做的,因为它很危险。
例如,我希望能够在 div 中显示的字符串中将单词“devil”的每个实例着色为红色。
如果不将文本转换为 html 元素,如何做到这一点?
【问题讨论】:
标签:
javascript
html
css
reactjs
frontend
【解决方案1】:
您可以使用replace 方法突出显示特定单词以及全局属性g 来替换所有单词
function highlight() {
var textHigh = document.getElementById("text")
textHigh.innerHTML = textHigh.innerHTML.replace(/ready/g, '<i style="color: red">ready</i>')
}
highlight();
<div id="text">I am everready for every ready state to keep the work ready</div>
【解决方案2】:
如果您想坚持使用 React(不直接修改 DOM),您可以遍历每个单词/标记并用 <span className="devil">devil<span> 替换单词 devil 但这会因标点符号等而变得棘手。不过这是一个开始。我认为@Rana 的解决方案可能最适合您想要做的事情。
<div style={{ color: "white" }}>{
textblockyouprovide.split(" ").map(word=>word=="devil"?<span className="devil">word</span>:word)
}</div>