Escape HTML before inserting it into page
Replace the five special characters before putting user text in markup, or use textContent so the browser never parses it, to stop cross-site scripting.
If you build HTML from user input with a template string, a name such as <img src=x onerror=alert(1)> becomes a live element. Escaping turns the special characters into harmless text.
function escapeHtml(text) {
return String(text)
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"')
.replaceAll("'", ''');
}
const name = '<img src=x onerror=alert(1)>';
console.log(`<p>Hello, ${escapeHtml(name)}</p>`);<p>Hello, <img src=x onerror=alert(1)></p>The ampersand has to be replaced first, otherwise the & inside the later replacements would be escaped again. The browser shows the escaped text as plain characters, and the onerror handler never runs.
The better habit is to avoid building markup from strings at all: set element.textContent = name, which treats the value as text and needs no escaping. Escaping is correct only for text and quoted attribute values; it does not make a value safe inside a <script> block, an href that can start with javascript:, or an inline style. Use a template engine that escapes by default, and a sanitizer such as DOMPurify when you must allow some HTML. See the OWASP XSS prevention cheat sheet.