【发布时间】:2016-01-26 01:03:04
【问题描述】:
我一直在寻找答案,但找不到适合我的特定用例的答案:由于 HTML 标记,我正在尝试使字符串中的所有匹配项(来自字典对象)显示为绿色。
特别是有一个案例我没有找到解决方法(在我的代码之后解释)。
var data = "cat fish";
var dictionary = {
"regex1": "cat",
"regex2": "cat fish"
}
function buildColoredString(data, dictionary) {
var coloredString = data;
for (var prop in dictionary) {
var toReplace = new RegExp(dictionary[prop].regex, "g");
var newString = "<b style='color: green;'>" + dictionary[prop].regex + "</b>";
coloredString = coloredString.replace(toReplace, newString);
}
console.log(coloredString);
}
在运行 buildColoredString 时,我只得到“cat”被 HTML 标签包围,而不是“cat fish”,因为它不匹配,因为 HTML 标签现在存在于我正在构建的字符串中。知道如何解决这个问题并让“猫”和“猫鱼”被 HTML 标签包围(我不介意是否有“太多”标签从视觉角度来看使其中一些无用。
感谢您的帮助,祝您有美好的一天!
【问题讨论】:
标签: javascript html regex