如何突出显示 div 中显示的字符串中的特定文本?
how to highlight specific text in a string displayed in a div?
<div
style={{ color: "white" }}
dangerouslySetInnerHTML={{
__html: `text <i style="color: red" >some data </i> not interesting`,
}}
/>
所以这是一种将字符串转换为 html 元素的方法。
这不是我想要做的,因为它很危险。
例如,我希望能够在 div 中显示的字符串中将单词“devil”的每个实例着色为红色。
如何在不将文本转换为 html 元素的情况下完成此操作?
您可以使用 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>
如果你想坚持使用 React(不直接修改 DOM),你可以遍历每个 word/token 并将单词 devil 替换为 <span className="devil">devil<span>
但这会变得棘手标点符号等。虽然这是一个开始。我认为@Rana 的解决方案可能最适合您的目标。
<div style={{ color: "white" }}>{
textblockyouprovide.split(" ").map(word=>word=="devil"?<span className="devil">word</span>:word)
}</div>
<div
style={{ color: "white" }}
dangerouslySetInnerHTML={{
__html: `text <i style="color: red" >some data </i> not interesting`,
}}
/>
所以这是一种将字符串转换为 html 元素的方法。
这不是我想要做的,因为它很危险。
例如,我希望能够在 div 中显示的字符串中将单词“devil”的每个实例着色为红色。
如何在不将文本转换为 html 元素的情况下完成此操作?
您可以使用 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>
如果你想坚持使用 React(不直接修改 DOM),你可以遍历每个 word/token 并将单词 devil 替换为 <span className="devil">devil<span>
但这会变得棘手标点符号等。虽然这是一个开始。我认为@Rana 的解决方案可能最适合您的目标。
<div style={{ color: "white" }}>{
textblockyouprovide.split(" ").map(word=>word=="devil"?<span className="devil">word</span>:word)
}</div>