简体   繁体   中英

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. the escaped characters are not supposed to be rendered like normal html, but rather as text. 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. I do not care if you add a jQuery solution, I just need a pure javascript one.

It doesn't work properly because you're replacing the ; s with <spans> . Try replacing the whole &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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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