转义字符不使用innerHTML

时间:2015-04-09 03:57:33

标签: javascript html

我有一个包含HTML转义字符(对于<>)的字符串,我试图使用innerHTML在div内呈现。转义字符不应该像普通的html一样呈现,而是作为文本呈现。但是,它们仍然存在,所以有解决方法吗?

注意:目标是将少数(意思不是全部)标记显示为普通文本。

以下是一个示例实现:

var string = "<div>yolo</div>";

string = string.replace(/</g, '&lt;'); //replaces all '<' with its escape character
string = string.replace(/>/g, '&gt;'); //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。

2 个答案:

答案 0 :(得分:4)

由于您将;替换为<spans>,因此无效。尝试先替换整个&lt; ,以防止您的span-replacer破坏实体。

e.g。

var string = "<div>yolo</div>";

string = string.replace(/</g, '&lt;'); //replaces all '<' with its escape character
string = string.replace(/>/g, '&gt;'); //replaces all '>' with its escape character

string = string.replace(/(&lt;|&gt;|=|%|\/|\*|-|,|;|\+|<|>)/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;
}

答案 1 :(得分:0)

如果你使用jQuery,你可能想要处理text()而不是innerHTML()