JavaScript/CSS - 查找具有特定表达式的文本并向其添加 css



我将以下文本存储在变量中:

var string = "[~Folky Bee] How are you today?";

我想做的是仅为分隔符 [~此处的文本] 中的文本添加一个类/样式,该类/样式将具有如下所示的最终输出:

民间蜜蜂你今天好吗?

到目前为止,我尝试执行以下操作:

var str = "[~Folky Bee] How are you today";
//Returns 1 (true) if the match is found (but I am getting wrong 
//results, maybe it's a wrong RegEx)
var n = str.search(/~/i);
//Then if the match is found add a color to it, but in this case I don't have 
//an id of that element so I can select it doing a .getElementById for example. 
//It's only a plain string.

您可以搜索带有波浪号的括号,并用样式替换内部组。

var string = "[~Folky Bee] How are you today?<br>[~Wham!] Fine!",
replaced = string.replace(/[~(.*?)]/g, '<span class="foo">$1</span>');
//                             ^^^        keeps value       ^^ 
console.log(replaced);
document.body.innerHTML += replaced;
.foo { font-weight: bold; }

最新更新