Skip to main content

Html

Escaping, unescaping, stripping and detecting HTML in strings. escapeHtml is the one to reach for on any untrusted value you are about to interpolate into markup — it replaces the five significant characters and is safe by construction. stripHtmlTags and containsHtml are regex-based conveniences for input you already trust; when you must keep markup intact, use a real sanitizer such as DOMPurify instead.

Example

import { escapeHtml, stripHtmlTags } from '@rtorcato/js-common/html'

// Anything user-supplied that lands in markup gets escaped first.
el.innerHTML = `<p>${escapeHtml(comment)}</p>`
// '<script>' -> '&lt;script&gt;'

// Plain-text preview of trusted rich text (an email digest, a search snippet).
stripHtmlTags('<b>hello</b> <i>world</i>') // 'hello world'

stripHtmlTags is regex-based, so it is a formatting convenience, not a sanitiser. To keep markup and make it safe, run DOMPurify.

Import

import { containsHtml, escapeHtml, stripHtmlTags } from '@rtorcato/js-common/html'

Exports

NameSummary
containsHtmlChecks if a string contains any HTML tags.
escapeHtmlEscapes special HTML characters in a string to prevent XSS attacks.
stripHtmlTagsStrips all HTML tags from a string.
textToHtmlConverts a plain text string to a simple HTML paragraph (newlines become <br> tags).
unescapeHtmlUnescapes HTML entities in a string.

See also

  • strings — slugify, truncate, casing, emoji stripping
  • security — password strength, secure tokens, sanitizing
  • regex — escape patterns, match-all, split by regex
  • validation — type guards — isString, isNumber, isUrl