Given a string with unsanitized HTML:
var unsanitizedHTML = '<script>alert("XSS");</script>';
You can sanitize the string using innerText
and innerHTML
:
var element = document.createElement('div');
element.innerText = unsanitizedHTML;
var sanitizedHTML = element.innerHTML;
This escapes the HTML entities to prevent XSS (cross-site scripting) attacks:
<script>alert("XSS");</script>
Helper function:
/**
* @param {string} text
* @return {string}
*/
function sanitizeHTML(text) {
var element = document.createElement('div');
element.innerText = text;
return element.innerHTML;
}
You can also clean the string using jQuery:
var sanitizedHTML = $('<div>').text(unsanitizedHTML).html();
Helper function:
/**
* @param {string} text
* @return {string}
*/
function sanitizeHTML(text) {
return $('<div>').text(text).html();
}