简体   繁体   English

转义字符不适用于innerHTML

[英]escape characters not working with innerHTML

I have a string containing HTML escape characters (for < and > ) that I am trying to render inside a div using innerHTML. 我有一个包含HTML转义字符(用于<> )的字符串,我正在尝试使用innerHTML在div内进行呈现。 the escaped characters are not supposed to be rendered like normal html, but rather as text. 转义的字符不应该像普通的html一样呈现,而是文本。 However, they still do, so is there a work around for this? 但是,他们仍然这样做,因此可以解决此问题吗?

NOTE: the objective is to display a few (meaning not all) tags as normal text. 注意:目的是将一些 (不是全部)标记显示为普通文本。

Here is an example implementation: 这是一个示例实现:

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;

PS please give an answer in pure JavaScript. PS请使用纯JavaScript给出答案。 I do not care if you add a jQuery solution, I just need a pure javascript one. 我不在乎是否添加jQuery解决方案,我只需要一个纯JavaScript的解决方案。

It doesn't work properly because you're replacing the ; 它不能正常工作,因为您要替换; s with <spans> . 带有<spans> Try replacing the whole &lt; 尝试替换整个&lt; first to prevent your span-replacer from breaking the entities. 首先,要防止您的跨距替换器破坏实体。

eg 例如

 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; } 

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM