How to sanitize HTML with JavaScript


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:

&lt;script&gt;alert("XSS");&lt;/script&gt;

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();
}


If you enjoyed this post, please consider supporting this site!