jQuery encode string to html entities

jQuery .text() method sets text for an element (after taking care of html entities) and .html() gets the html for a dom element. Combining these we can encode a string to html entities.

var encoded = $("<div/>").text(str).html();

Here is example code for it.

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

<pre id="log"></pre>

<script type="text/javascript">
var str = '<span>hello world</span>';
var encoded = $("<div/>").text(str).html();
console.log("str: " + str);
console.log("encoded: " + encoded);
$("#log").text("str: " + str + "\n" + "encoded: " + encoded);
</script>
refresh

The console outcome from above is:
jqyery-html-entities-console-output

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments