Reputation: 203
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, '<'); //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. please give an answer in pure JavaScript. I do not care if you add a jQuery solution, I just need a pure javascript one.
Upvotes: 1
Views: 3607
Reputation: 282875
It doesn't work properly because you're replacing the ;
s with <spans>
. Try replacing the whole <
first to prevent your span-replacer from breaking the entities.
e.g.
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;
}
Upvotes: 4
Reputation: 3653
If you use jQuery, you may want to deal with text()
instead of innerHTML()
.
Upvotes: -1