tags:

views:

6028

answers:

6

How do you use jquery to decode html entities in a string? or how do I stop jquery from encoding a string with html entities in the first place?

+2  A: 

I think you're confusing the text and html methods. Look at this example, if you use an element's inner html as text, you'll get decoded html tags (second button). But if you use them as html, you'll get html formatted view (first button).

<div id="myDiv">
    here is a <b>HTML</b> content.
</div>
<br />
<input value="Write as HTML" type="button" onclick="javascript:$('#resultDiv').html($('#myDiv').html());" />
&nbsp;&nbsp;
<input value="Write as Text" type="button" onclick="javascript:$('#resultDiv').text($('#myDiv').html());" />
<br /><br />
<div id="resultDiv">
    Results here !
</div>

First button writes : here is a HTML content.

Second button writes : here is a <B>HTML</B> content.

By the way, you can see a plug in that I found at web here that encodes & decodes HTML strings.

Canavar
+1  A: 

Since this is the one of the top results in Google for javascript htmlentities decode, I'll clarify the question, though I don't know yet if their is an answer. The question is not, as suggested in another answer, how to prevent jquery from rendering html tags. The question clearly involves how to convert HTML tags to entities and back using javascript. e.g. how to change &lt; into "<"

I'm trying to answer the same question...

A: 

myString = myString.replace( /\&/g, '&' );

easiest to do it on the server side because apparently Javascript has no native library for handling entities, nor did I find any near the top of search results for the various frameworks that extent JS. Search for "javascript html entities" and you might find a few libraries for just that purpose, but they'll probably all be built around the above logic -- replace, entity by entity.

A: 

var decoded = $('').html(encoded).val();

lucascaro
This didn't work for me.
Senseful
+14  A: 

actually, try

var decoded = $("<div/>").html(encodedStr).text();
tom
This one WORKS!
mhughes
Works great. Nice and elegant. :)
nickb
thanks a lot! worked for me too
Purefan
A: 
philipp