我有一个字符串,其中包含HTML转义字符(用于<
和>
),我试图使用innerHTML在div
中呈现这些字符。转义字符不应呈现为普通html,而应呈现为文本。然而,他们仍然这样做,因此,是否有一个工作围绕这一点?
注意:目标是以普通文本的形式显示几个(意思不是全部)标记。
下面是一个实现示例:
var string = "<div>yolo</div>";
string = string.replace(/</g, '<'); //replaces all '<' with its escape character
string = string.replace(/>/g, '>'); //replaces all '>' with its escape character
string = string.replace(/(=|%|\/|\*|-|,|;|\+|<|>)/g, "<span class=\"sc\">$1</span>");
//the last line adds special formatting
//to certain characters using CSS (not shown)
//and a span tag with class, "sc".
//this is the reason that I cannot just simply
//use innertext instead of innerhtml
document.body.innerHTML = string;
P.S.请用纯JavaScript回答。我不在乎您是否添加了一个jQuery解决方案,我只需要一个纯的javascript解决方案。
发布于 2015-04-09 04:04:49
它不能正常工作,因为您要用;
替换<spans>
。尝试首先替换整个<
,以防止span替换器破坏实体。
例如:
var string = "<div>yolo</div>";
string = string.replace(/</g, '<'); //replaces all '<' with its escape character
string = string.replace(/>/g, '>'); //replaces all '>' with its escape character
string = string.replace(/(<|>|=|%|\/|\*|-|,|;|\+|<|>)/g, "<span class=\"sc\">$1</span>");
//the last line adds special formatting
//to certain characters using CSS (not shown)
//and a span tag with class, "sc".
//this is the reason that I cannot just simply
//use innertext instead of innerhtml
document.body.innerHTML = string;
.sc {
color: red;
font-weight: bold;
}
发布于 2015-04-09 04:00:28
如果使用jQuery,您可能需要处理text()
而不是innerHTML()
。
https://stackoverflow.com/questions/29529472
复制相似问题