首页 > 解决方案 > 使用不同颜色突出显示文本字符串中的特定单词

问题描述

我从 api 获取一个字符串和一个字符串数组,例如如下所示。(这些字符串和数组是动态的)

samplestring = "You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth.";

samplearray = dance,love,sing (The count is also dynamic)

如果它们在 samplestring 中,我想突出显示来自 samplearray 的字符串,

就像是

在此处输入图像描述

无论如何通过css或js来实现这一点?

我看到了这个问题,但我不能使用它,因为我的字符串是动态的。我也看到了这个问题,但我不确定如何实施。

标签: javascripthtmlcss

解决方案


您可以搜索每个单词并用标签替换源字符串。设置它使用innerHTML

var samplestring = "You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth.";

const samplearray = ["dance","Love","Sing"]

samplearray.forEach(str => {
  samplestring = samplestring.replaceAll(str, `<span>${str}</span>`)
})

root.innerHTML = samplestring
span {
  color: red
}
<div id="root"></div>


推荐阅读