JavaScript: preventing XSS by escaping output

Cross-site scripting (XSS) happens when a page inserts untrusted text into HTML without encoding it. An attacker submits a comment such as an img tag with an onerror handler, and the browser runs the script in every visitor's session. The fix is to encode output for the context it is inserted into.

JavaScript
const entities = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };

function escapeHtml(text) {
  return text.replace(/[&<>"']/g, (ch) => entities[ch]);
}

const comment = '<img src=x onerror="alert(1)">';
console.log("<p>" + comment + "</p>");
console.log("<p>" + escapeHtml(comment) + "</p>");
console.log("<p>" + escapeHtml("Tom & Jerry") + "</p>");
Read the full lesson