Security

import {
  escapeHtml, unescapeHtml, escapeRegExp, stripTags,
  collapseWhitespace, stripPrefix, stripSuffix,
} from '@ppabari/strio/str';
โš ๏ธ

Not a full sanitizer: escapeHtml / stripTags provide basic protection for text interpolation. They are not a substitute for a full HTML sanitizer (e.g. DOMPurify) when rendering untrusted rich markup.

escapeHtml / unescapeHtml

escapeHtml(str: string): string
unescapeHtml(str: string): string

Escape (and reverse) the five HTML-significant characters & < > " '.

escapeHtml('<a href="x">Tom & Jerry</a>');
// โ†’ '&lt;a href=&quot;x&quot;&gt;Tom &amp; Jerry&lt;/a&gt;'
unescapeHtml('&lt;b&gt;hi&lt;/b&gt;'); // โ†’ '<b>hi</b>'

escapeRegExp

escapeRegExp(str: string): string

Escape a string so it can be used literally inside a RegExp.

escapeRegExp('a.b*c'); // โ†’ 'a\\.b\\*c'
new RegExp(escapeRegExp('$5.00')).test('$5.00'); // โ†’ true

stripTags

stripTags(str: string): string

Remove all HTML/XML tags, leaving the text content.

stripTags('<p>Hello <b>world</b></p>'); // โ†’ 'Hello world'

collapseWhitespace

collapseWhitespace(str: string): string

Collapse all runs of whitespace into a single space and trim the ends.

collapseWhitespace('  a\n\t  b   c '); // โ†’ 'a b c'

stripPrefix / stripSuffix

stripPrefix(str: string, prefix: string): string
stripSuffix(str: string, suffix: string): string

Remove an affix only if present. Idempotent.

stripPrefix('usr_123', 'usr_'); // โ†’ '123'
stripSuffix('report.txt', '.txt'); // โ†’ 'report'
stripSuffix('report', '.txt');     // โ†’ 'report'