JohnDoe22366 JohnDoe22366 - 4 months ago 21
jQuery Question

Replace < and > in jquery

I am trying to replace "<" and ">" in jquery in order to display to human being for example.
I'd like it to do it after initialisation.
Any idea?

var el = $("#mydiv").clone();
el.text().replace(new RegExp("<", 'g'), "&lt;");
el.html().replace(new RegExp(">", 'g'), "&gt;");
$("mydiv").after(el);

Answer

It would be easier to call .html() on your element and save it to .text();

var el = $("#mydiv").clone();
$(el).text($(el).html());
$("#mydiv").after(el);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv">I'm a <span style="color:red">test</span></div>

Comments