Jerry Jones
Jerry Jones

Reputation: 796

Sanitize codes injection using jQuery

I am using a comment box and insert the value to mysql using ajax. Same time I append the entered comment with jQuery to the same page. The problem is if the entered text is some JavaScript code, like

<script>alert('hello');</script>

it shows the alert. In my database I sanitize these code but since I append it in client side I need to display the entered text like it is.

Well I use,

<div contenteditable="true"></div>

Any immediate help, please?

Upvotes: 2

Views: 404

Answers (2)

Jerry Jones
Jerry Jones

Reputation: 796

I used this method!

str.replace(/</g, "&lt;");
str.replace(/>/g, "&gt;");

Upvotes: 0

Maksym Kozlenko
Maksym Kozlenko

Reputation: 10363

The following snippet HTML encodes string to:

"&lt;div&gt;Here is an HTML&lt;/div"


$("p").text("<div>Here is an HTML</div").html()

Upvotes: 1

Related Questions