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?

2
  • your final export: <p>name</p><p><span style="font-size:xx-small;">ajde</span></p><p><em>da</em></p></body> Commented May 23, 2012 at 8:07
  • Easiest way is to assign a class selector to your element and then use this code $('.selector').each(function(a,b){$(b).html($(b).text())}) Commented Jan 23, 2013 at 11:32

4 Answers 4

174
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 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.

Sign up to request clarification or add additional context in comments.

6 Comments

What if the text is "><img src=x onerror=prompt(1)>?
don't use $('<div/>') - i't make posible XSS atack. Use $('<textarea/>');
I'm not sure if this is also proper (I'm using jQuery 2.x): $.parseHTML(text)[0].textContent;
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 $('<textarea/>').html(text).html()
It's a very bad idea because is allowing HTML injection. for example if in the incoming text you have something like this: <script>alert(code injection')</script> it will show an alert on the user screen.
|
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().

1 Comment

not working in firefox
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/

1 Comment

Same as the other two answers. You'll get a badge of honor if you delete the answer :)
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();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.