Escape HTML Special Characters
Escape ampersands, angle brackets, quotes and newlines before inserting untrusted values into HTML or attributes.
Code
const HTML_ENTITIES = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
};
export function escapeHtml(value) {
return String(value).replace(/[&<>"']/g, (character) => HTML_ENTITIES[character]);
}
export function escapeHtmlAttribute(value) {
return escapeHtml(value).replace(/\r?\n/g, " ");
}
export function escapeHtmlTemplate(strings, ...values) {
return strings.reduce((output, chunk, index) => {
const value = index < values.length ? escapeHtml(values[index]) : "";
return output + chunk + value;
}, "");
}How it works
Escape HTML Special Characters keeps everything in the functions escapeHtml, escapeHtmlAttribute and escapeHtmlTemplate.
Putting it to use
The entry-point signature is export function escapeHtml(value)
escapeHtml is the public entry point; everything else in the file exists to support it.
Core lines
return strings.reduce((output, chunk, index) => {
const value = index < values.length ? escapeHtml(values[index]) : "";
return output + chunk + value;
}, "");
return String(value).replace(/[&<>"']/g, (character) => HTML_ENTITIES[character]);
return escapeHtml(value).replace(/\r?\n/g, " ");
Interactive Tools for This Topic
HTML Entity Encoder / DecoderEncode the five HTML-significant characters and decode named or numeric entities, with optional numeric encoding for non-ASCII text.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.
FAQ
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. The file defines `escapeHtml`, `escapeHtmlAttribute`, `escapeHtmlTemplate` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.