Benjamin W Benjamin W - 18 days ago 5
Javascript Question

javascript display htmlentities tag

var foo = $('.imgEscape').text();
foo = foo.replace("&lt;img src=&quot;", "<img src='");
foo = foo.replace("&quot; /&gt;", "' />");
$('.imgEscape').text(foo);//will display as string
$('.imgEscape').html(foo);//will display all html tag

&lt;img src=&quot;https://www.google.com.tw/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png&quot; /&gt;
&lt;b&gt;abc&lt;/b&gt


I have a page backend output data as htmlspecialcharacter.

I wish to use js to replace some tag (ex. img tag)

so I can still display image

my problem is if I use
html()
, it will display all element.

I wish to display image only (
<img> ... &lt;b&gt;abc&lt;/b&gt
)

anyone know how to do this?

Answer

The text() method returns the parsed text data so String#replace method is doing nothing since the content is parsed string. Instead you need to get the actual HTML content content using html() method .

var foo = $('.imgEscape').html();
// update here -----------^^^^^^----
foo = foo.replace("&lt;img src=&quot;", "<img src='");
foo = foo.replace("&quot; /&gt;", "' />");
$('.imgEscape').html(foo);