64

Possible Duplicate:
How to decode HTML entities using jQuery?

I want to convert this text:

"<p>name</p><p><span style="font-size:xx-small;">ajde</span></p><p><em>da</em></p>"

to html, with tags and everything in Javascript or Jquery. How to do this?

Community
  • 1
  • 1
petko_stankoski
  • 10,459
  • 41
  • 127
  • 231

4 Answers4

172
var text = '<p>name</p><p><span style="font-size:xx-small;">ajde</span></p><p><em>da</em></p>';
var decoded = $('<textarea/>').html(text).text();
alert(decoded);

This sets the innerHTML of a new element (not appended to the page), causing jQuery to decode it into HTML, which is then pulled back out with .text().

Live demo.

wersimmon
  • 2,809
  • 3
  • 22
  • 35
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 3
    What if the text is `">`? – viky Nov 20 '13 at 08:56
  • 40
    don't use `$('
    ')` - i't make posible XSS atack. Use `$('');`
    – trijin Feb 20 '14 at 23:04
  • 2
    I'm not sure if this is also proper (I'm using jQuery 2.x): `$.parseHTML(text)[0].textContent;` – Ricky Mar 09 '15 at 04:08
  • When encoded string contains *Enter* sign between tags, this returns just *Enter* instead of html (at least in Chrome). to fix it I changed solution to `$('').html(text).html()` – Sasha Oct 06 '15 at 10:21
  • It's a very bad idea because is allowing HTML injection. for example if in the incoming text you have something like this: `` it will show an alert on the user screen. – Josh May 03 '19 at 09:47
  • that's why you have to sanitize the text first ` – Kevin Chandra Jul 21 '23 at 03:50
18

There is a jQuery solution in this thread. Try something like this:

var decoded = $("<div/>").html('your string').text();

This sets the innerHTML of a new <div> element (not appended to the page), causing jQuery to decode it into HTML, which is then pulled back out with .text().

Community
  • 1
  • 1
Bojangles
  • 99,427
  • 50
  • 170
  • 208
11

Using jQuery the easiest will be:

var text = '&lt;p&gt;name&lt;/p&gt;&lt;p&gt;&lt;span style="font-size:xx-small;"&gt;ajde&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;em&gt;da&lt;/em&gt;&lt;/p&gt;';

var output = $("<div />").html(text).text();
console.log(output);

DEMO: http://jsfiddle.net/LKGZx/

VisioN
  • 143,310
  • 32
  • 282
  • 281
3

I think you are looking for this ?

$('#your_id').html('&lt;p&gt;name&lt;/p&gt;&lt;p&gt;&lt;span style="font-size:xx-small;"&gt;ajde&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;em&gt;da&lt;/em&gt;&lt;/p&gt;').text();
Kaidul
  • 15,409
  • 15
  • 81
  • 150