An Original Alias
An Original Alias

Reputation: 203

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;

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

Answers (2)

mpen
mpen

Reputation: 282875

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.

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

Upvotes: 4

Amar Syla
Amar Syla

Reputation: 3653

If you use jQuery, you may want to deal with text() instead of innerHTML().

Upvotes: -1

Related Questions