Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Security boundaries: HTML text escaping versus sanitization

A security boundary separates untrusted data from operations that give it meaning or authority. Learn the difference between HTML text escaping and allowlist sanitization, and understand the limits of a small JavaScript escaping example.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

escapeHtmlText(value); // HTML text context only; not an HTML sanitizer

A security boundary (security boundaries) is a point where lower-trust data reaches an operation that can interpret it as code or markup. Input does not become trusted merely because it is a JavaScript string. ECMAScript defines the language, while HTML parsing and browser protections belong to the host environment; the supplied specification is not an HTML sanitization standard.

HTML text escaping versus allowlist sanitization: escaping replaces special characters with character references so that content is treated as text rather than markup. Sanitization serves a different purpose: it permits selected markup while removing or rejecting disallowed elements, attributes, and unsafe URL values. Do not replace a sanitizer with a simple regular expression that strips tags.

The escapeHtmlText function accepts a string and escapes &, <, and > in one pass. Its scope is only an ordinary HTML text context, not attributes, URLs, JavaScript, CSS, or the contents of script and style elements. Quotation marks intentionally remain unchanged. The result is not “safe HTML” for arbitrary use; escaping an already escaped result changes it again.

The example checks only a deterministic string transformation and requires no browser API. It neither demonstrates rendering nor verifies a sanitizer. An application that must preserve HTML formatting needs a separately selected and verified sanitization policy. Running code in Node.js does not establish browser API availability or security.

Examples

function escapeHtmlText(value) {
  const entities = { "&": "&amp;", "<": "&lt;", ">": "&gt;" };
  return value.replace(/[&<>]/g, character => entities[character]);
}

const input = '<b>Hello</b> & "friends"';
const actual = escapeHtmlText(input);
const expected = '&lt;b&gt;Hello&lt;/b&gt; &amp; "friends"';
if (actual !== expected) {
  throw new Error("Unexpected escaping result");
}
console.log(actual);

Result

&lt;b&gt;Hello&lt;/b&gt; &amp; "friends"

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources