gpt4 book ai didi

Javascript - 如何在文本字符串中设置特定单词的样式?

转载 作者:行者123 更新时间:2023-12-03 07:02:32 27 4
gpt4 key购买 nike

我在这里有一串文本,它将被动态生成为以下之一:

<h1 id="headline">"Get your FREE toothbrush!"</h1>

OR

<h1 id="headline">"FREE floss set and dentures!"</h1>

由于这将是动态生成的,我将无法包装 <span>围绕“FREE”这个词,所以我想使用 Javascript 专门针对“FREE”这个词,这样我就可以使用与 <h1> 不同的字体系列和字体颜色来设置它的样式被设定为。我使用什么方法来做到这一点?

最佳答案

您可以使用样式化的 HTML 搜索和替换子字符串“FREE”。如果字符串中多次出现“FREE”,您可能需要使用正则表达式(除非您不需要支持 Internet Explorer)。见 How to replace all occurrences of a string?

在你的情况下:

let str = '<h1 id="headline">"FREE floss set and dentures!"</h1>'
str = str.replace(/FREE/g, '<span color="red">FREE</span>');

关于Javascript - 如何在文本字符串中设置特定单词的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64671946/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com