Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Escaping text in HTML

When generating HTML, escape plain text for the position where it will be inserted. When writing directly to an ordinary DOM element, use `textContent` with the original string instead.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

const escapeHtmlText = (text) => text.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
// Use escaped text only in the ordinary text position of trusted HTML markup.
const markup = `<p>${escapeHtmlText(text)}</p>`;
// If writing directly to an ordinary DOM element, use the original string instead.
element.textContent = text;

HTML text-context escaping is output encoding for plain text inserted into HTML source, such as the content of a p element. A raw < can open a tag, and & can start a character reference. The parser turns &lt; into a literal < in the text; it does not treat that decoded character as the start of a tag.

When chaining replaceAll calls, replace & with &amp; before replacing < with &lt;, so you don't escape the ampersands introduced by later replacements. The example also replaces > with &gt;, which is optional here; quotes do not need escaping in this context either. Encode the raw text once, where it is inserted, and skip manual encoding if the template already does it.

To set the text of an ordinary DOM element, assign the original string to textContent. Do not pass that string to innerHTML for this purpose: it parses markup. Do not reuse this helper for attributes, URLs, JavaScript, or CSS; those contexts have different rules. If you need to preserve some markup from untrusted HTML, use HTML sanitization instead of text escaping.

Examples

function escapeHtmlText(text) {
  return text.replaceAll('&', '&amp;')
    .replaceAll('<', '&lt;')
    .replaceAll('>', '&gt;');
}

const text = 'A & B <em>demo</em> &lt;';
console.log(`<p>${escapeHtmlText(text)}</p>`);

Result

<p>A &amp; B &lt;em&gt;demo&lt;/em&gt; &amp;lt;</p>

The console prints HTML source, not rendered text. Parsing it produces a paragraph with no `em` element, and the final `&lt;` remains literal text.

Related lessons

  • JavaScript · Lesson 28 · Advanced · Version: 4

Sources