Skip to content

escapeHtml

Escapes the HTML special characters &, <, >, ", and ' in a string.

Use this to safely embed untrusted content into HTML attribute values or text nodes without risk of XSS injection.

Available since v2.0.0

import { escapeHtml } from '@helpers4/string';
// or, from the all-in-one package (same code, one install):
import { escapeHtml } from 'helpers4/string';
escapeHtml(str: string): string
ParameterTypeDescription
strstringThe string to escape.

string — The escaped string.

Converts < > ” ’ & to their HTML entities to prevent XSS.

escapeHtml('<script>alert("xss")</script>')
// => '&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;'

Safe for inserting untrusted strings into HTML.

const userInput = '<b>bold</b>';
escapeHtml(userInput) // => '&lt;b&gt;bold&lt;/b&gt;'

View source on GitHub