javascript - 使用不同颜色突出显示文本字符串中的特定单词
问题描述
我从 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来实现这一点?
解决方案
您可以搜索每个单词并用标签替换源字符串。设置它使用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>
推荐阅读
- javascript - 如何为引导模式一起触发 2 个事件?
- ios - 重新排序时在 tableviewcell 上添加阴影
- javascript - 如何将 co.wrap 与生成器一起使用
- ruby-on-rails - jsonb 保存数组列 jsonb postgres rails
- python - 使用 Lambda 从 base64 上传 s3
- gcc - 如何在 Qt 中禁用 mingw 的优化
- git - git remote push origin 已更改且无法重置
- python - QML 应用程序在 QApplication.exec() 上冻结并且不显示窗口
- node.js - 在 NodeJS 中设置不记名令牌
- json - 公开 Oracle 数据库中的数据以供 Web 服务使用