Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent jQuery from escaping html entities

I have some simple html editor. Let's say that user types following:

<p>Ok, this just &amp; sucks :) &ndash;</p>

and it is saved to some variable:

var content = "<p>Ok, this just &amp; sucks :) &ndash;</p>";

Now, somewhere I'm using jQuery to append this text to some element:

$(this).html(content); // where content is the string above

The problem is that it is escaped:

<p>Ok, this just &amp;amp; sucks :) &amp;ndash;</p>

How can I achieve to have the exact string with &amp ; and &ndash ; and also to have < and not &lt ; because I need html tags?

Edit: more details added

like image 364
ladar Avatar asked Oct 14 '11 21:10

ladar


People also ask

How do I stop HTML from escaping?

The html_safe method marks a string as being safe for insertion into HTML without escaping being performed.

Why is HTML escaping?

Escapes are very useful for representing characters that are not apparent or are ambiguous. Numeric or named character references, as well as CSS escapes, can be used to represent characters in HTML style attribute. The style element HTML can not contain numeric or named character references.


2 Answers

The problem is not that jQuery is escaping the entities. I think if you use console.log to write the content string, you'll see that your editor is returning escaped entities to you.

The whole point of .html() vs .text() is that .html() is for HTML that will be treated as HTML.

like image 151
Ned Batchelder Avatar answered Nov 01 '22 23:11

Ned Batchelder


I Guess you want to have the text <p>Ok, this just &amp;amp; sucks :) &amp;ndash;</p> to be exactly shown with out converting them, so that the &amp; and ndash; will not be converted to & and -, then use :

$(this).text(content);

One problem with this is that the content will be added as a text in site the this element. It will not create a p element and append it to this.

But if you want to take the effect of conversion then you code should work.

One more thing I want to mention, I believe that language is not the only one related to those conversion. Browser take the main role in those cases. SO, What ever we do in the script if browser get another chance to check the contents it will convert them to & and -.

like image 45
Saif Avatar answered Nov 01 '22 22:11

Saif