Drew Coffin February 2016

Why does using replace to unescape html tags strips out all other html tags as well?

I need to convert &lt; and &gt; in a table to < and >. The function I'm using to do this works well.

<div class="schedule">    
          <td>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.&lt;br /&gt;
            <em>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</em>&lt;br /&gt;Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</td>


$('.table-container td').each(function(){
  var $this = $(this);
  var t = $this.text();
  $this.html(t.replace('&lt','<').replace('&gt', '>'));

However, this function also removes the <em> tags that don't need any unescaping. Anyone know why?



Draco18s February 2016

Because you used .text() to get your HTML content.

Use .html() instead:

var t = $this.html();


charlietfl February 2016

Shortcut method using html(function) to replace the each loop

$('.table-container td').html(function(_,existing){
     return existing.replace('&lt;','<').replace('&gt;', '>');


nicdford February 2016

When you're using replace() i've found it only replaces the first instance. If you use regex you can set it to replace every instance of &lt; and &gt; with /g


Post Status

Asked in February 2016
Viewed 3,291 times
Voted 13
Answered 3 times


Leave an answer