user3548161 user3548161 - 6 months ago 38
jQuery Question

Jquery stop rendering Html syntax escape javascript variable

I have a Ordered list with a class named as comments.

So i am pushing values from my text area into a variable named my_html_syntax.

The code works fine the only problem is how do I stop html syntax from rendering
for example when i enter html syntax for a buttton it renders the button into my ul.

how do i escape my javascript variable my_html_syntax

SOLVED -thanks to justinas this is how i used it .

<html>

<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>

<javascript type="text/javascript">

var my_html_syntax= $('#textarea').val();

function htmlEntities(str) {
return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}


$('.comments').append('<li>' + htmlEntities( my_html_syntax) +'</li>');

</javascript>

</head>
<body>
<ul classs="comments"> </ul>

</body>

</html>

Answer

You can escape HTML entities to be shown:

function htmlEntities(str) {
  return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

$(document).ready(function() {
  $('ul').append("<li>" + htmlEntities("<a href='example.com'>LINK</a>") + "</li>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul></ul>

Source