Skip to content

HTML Processing

Functions for processing HTML strings: removing tags, escaping characters, parsing, and cleaning fragments.

Method List

HTML Cleaning

FunctionSignatureDescription
stripHtml(string: string): stringRemoves all HTML tags from a string.
stripFragment(html: string): stringRemoves fragment tags from an HTML string.

HTML Escaping and Decoding

FunctionSignatureDescription
escapeHtml(input: string): stringConverts special characters to HTML entities.
decodeHtml(input: string): stringConverts HTML entities back to characters.

HTML Parsing

FunctionSignatureDescription
parseHtml(html: string, isStripFragment?: boolean): Node[]Parses an HTML string into an array of DOM nodes.

Usage Examples

HTML Cleaning

1. stripHtml

typescript
import { stripHtml } from 'snappykit';

const htmlString = '<p>Hello, <strong>world!</strong></p>';
console.log(stripHtml(htmlString)); // "Hello, world!"

2. stripFragment

typescript
import { stripFragment } from 'snappykit';

const htmlWithFragment = '<!--StartFragment--><p>Text fragment</p><!--EndFragment-->';
console.log(stripFragment(htmlWithFragment)); // "<p>Text fragment</p>"

HTML Escaping and Decoding

3. escapeHtml

typescript
import { escapeHtml } from 'snappykit';

const unsafeString = '<script>alert("XSS")</script>';
console.log(escapeHtml(unsafeString)); // "&lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;"

4. decodeHtml

typescript
import { decodeHtml } from 'snappykit';

const encodedString = '&lt;p&gt;Hello, world!&lt;/p&gt;';
console.log(decodeHtml(encodedString)); // "<p>Hello, world!</p>"

HTML Parsing

5. parseHtml

typescript
import { parseHtml } from 'snappykit';

const htmlString = '<div><p>Hello</p><span>World</span></div>';
const nodes = parseHtml(htmlString);
console.log(nodes.length); // 2 (nodes <p> and <span>)

// With fragments
const htmlWithFragment = '<!--StartFragment--><p>Fragment</p><!--EndFragment-->';
const fragmentNodes = parseHtml(htmlWithFragment, true);
console.log(fragmentNodes.length); // 1 (node <p>)

dev@priveted.com | priveted.com